Sending a JSON file to Express server using JS

后端 未结 4 1118
难免孤独
难免孤独 2021-02-07 14:03

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.

4条回答
  •  渐次进展
    2021-02-07 14:37

    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

提交回复
热议问题