Sending A Json File To Express Server Using Js
Solution 1:
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
Solution 2:
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.
Solution 3:
Try res.json(data.json) instead of res.send(...
Solution 4:
Because __dirname
resolves to where your script is running I prefer using path.resolve()
var path = require('path');
app.get('/search', (req, res) => {
res.header("Content-Type",'application/json');
res.sendFile(path.resolve('search/data.json'));
})
Solution 5:
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));
});
Post a Comment for "Sending A Json File To Express Server Using Js"