Sending JSON file to Express server using JS

I am new to JS and I have a JSON file that I need to send to my server (Express), after which I can parse and use its contents throughout the entire web application I create.

Here's what I have now:

  • a JSON file named data.json
  • configured Express server running on local hosting
  • some crappy code:

    app.get ('/ search', function (req, res) {res.header ("Content-Type", 'application / JSON'); res.send (JSON.stringify ({/ data.json /})) ;});

In the code above, I am just trying to send a file to localhost: 3000 / search and see my JSON file, but all I get when I go this path is {}. Can someone please explain?

Any help would be much appreciated. Thank you very much in advance.

Cheers, Theo

Sample snippet from data.json:

[{
    "name": "Il Brigante",
    "rating": "5.0",
    "match": "87",
    "cuisine": "Italian",
    "imageUrl": "/image-0.png"
}, {
    "name": "Giardino Doro Ristorante",
    "rating": "5.0",
    "match": "87",
    "cuisine": "Italian",
    "imageUrl": "/image-1.png"
}]

      

+3


source to share


3 answers


Just make sure you need the correct file as a variable and then pass that variable to res.send!

const data = require('/path/to/data.json')

app.get('/search', function (req, res) {
  res.header("Content-Type",'application/json');
  res.send(JSON.stringify(data));
})

      



Also, my personal preference is to use res.json

it as it sets the title automatically.

app.get('/search', function (req, res) {
  res.json(data);
})

      

+4


source


Try res.json (data.json) instead of res.send (...



+1


source


Read the file first and then send the json to the client.

fs.readFile('file_name.json', 'utf8', function (err, data) {
  if (err) throw err;
  obj = JSON.parse(data);
  res.send(JSON.stringify(obj));
});

      

0


source







All Articles