Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending a JSON file to Express server using JS

I am fairly new to JS and I have a JSON file that I need to send to my server (Express) that I can then parse and use its contents throughout the web app I'm building.

Here's what I have now:

  • a JSON file named data.json
  • an Express server set up that is running on a localhost
  • some shitty 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 the file to localhost:3000/search and see my JSON file, but all I receive when I go to that path is { }. Can anyone explain?

Any help would be immensely appreciated. Thanks so much in advance.

Cheers, Theo

Example 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"
}]
like image 295
Theo Strauss Avatar asked Jun 30 '17 14:06

Theo Strauss


3 Answers

Just make sure you're requiring the correct file as a variable and then pass that variable into your 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 as it sets the header automatically.

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

EDIT:

The drawback to this approach is that the JSON file is only read once into memory. If you don't want the file read into memory or you're planning on modify the JSON on disk at some point then you should see Ian's Answer

like image 158
Khauri Avatar answered Nov 15 '22 10:11

Khauri


Another option is to use sendFile and set the content type header.

app.get('/search', (req, res) => {
    res.header("Content-Type",'application/json');
    res.sendFile(path.join(__dirname, 'file_name.json'));
})

The code assumes the file is in the same directory as the JS code. This answer explains how this works.

like image 31
Ian Avatar answered Nov 15 '22 08:11

Ian


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

like image 2
user5480949 Avatar answered Nov 15 '22 08:11

user5480949