Home
Support Forums

How to access static file api server build on nodejs

Hi am new to netlify…

I am trying to build a simple API server build using nodejs which is working fine in my local i can able to get the response on browser but the same code if i tried to deploy in netlify it says

{
  "errorType": "Error",
  "errorMessage": "ENOENT: no such file or directory, open './src/data/testData.json'",
  "trace": [
    "Error: ENOENT: no such file or directory, open './src/data/testData.json'"
  ]
}

netlify.toml

[build]
  functions = "functions"

[dev]
  publish = "dist"

api.js

var express = require("express");

const bodyParser = require("body-parser");

const fs = require("fs");

const serverless = require("serverless-http");

var app = express();

const router = express.Router();

app.use(function (req, res, next) {

  res.header("Access-Control-Allow-Origin", "*");

  res.header(

    "Access-Control-Allow-Headers",

    "Origin, X-Requested-With, Content-Type, Accept"

  );

  next();

});

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: true }));

// variables

// const Udemy_Coupen = __dirname + '/data/Udemy_coupen.json';

// TestData

const Test_Data = './src/data/testData.json';

router.get('/', (req, res) => {

  fs.readFile(Test_Data, 'utf8', (err, data) => {

      if (err) {

          throw err;

      }

        let jsondata = JSON.parse(data)

      let modifiedData = jsondata.map((val,ind)=>(

        {

        id : ind,

        courseidhref:val.courseidhref,

        courseTitle : val.courseidhref.replace(/-/g, ' ').split('?')[0].split('/').reverse()[1]

        }

        ));

      res.send(modifiedData);

  });

});

router.get("/test", (req, res) => {

  res.send("Welcome to the homepage!");

});

// // finally, launch our server on port 3001.

// const server = app.listen(3000, () => {

//   console.log("listening on port %s...", server.address().port);

// });

app.use("/.netlify/functions/api", router);

module.exports = app;

module.exports.handler = serverless(app);

here find my project structure
image

please help me to resolve this issue

Hi! Welcome to the Netlify community forum! Unfortunately, you can’t run a server on Netlify, it’s meant for hosting static sites. You can find more about that here:

1 Like