I want to make a GET request to a local JSON file with express.
In my server.js I have this
var data = {};
app.get('/src/assets/data.json', (req, res) => {
console.log(res)
res.writeHead(200, {
'Content-type': 'application/json'
});
res.end(JSON.stringify(data));
});
data.json looks like this
[{
"param": "one",
"param": "two",
"param": "three"
}]
Also I made a function for GET request which is called as soon as the DOM is loaded
getData() {
let xhr = new XMLHttpRequest();
xhr.open('GET', '/src/assets/data.json', true);
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log(xhr)
}
};
xhr.send();
}
I'm getting a response back but it is an empty object. I'm guessing it is because in my server file var data = {};
is empty but I'm not sure what to do with it?
Express has a built-in express. json() function that returns an Express middleware function that parses JSON HTTP request bodies into JavaScript objects. The json() middleware adds a body property to the Express request req . To access the parsed request body, use req.
Why don't you simply just send the file you requested for
var data = {};
app.get('/src/assets/data.json', (req, res) => {
console.log(res)
/* Insted of doing all this */
// res.writeHead(200, {
// 'Content-type': 'application/json'
// });
// res.end(JSON.stringify(data));
/* Just send the file */
res.sendFile(path.join(__dirname, '/src/assets', 'data.json'));
});
But if you want to just do as your code, what you need to include in your code is
data.json
file.data
variable.To read the file, you need to include File System module of Node.js
Sync:
var fs = require('fs'); /* Put it where other modules included */
var data = JSON.parse(fs.readFileSync('/src/assets/data.json', 'utf8')); /* Inside the get function */
Async:
var fs = require('fs');
var data;
fs.readFile('/src/assets/data.json', 'utf8', function (err, data) {
if (err) throw err;
data = JSON.parse(data);
});
Please read the official documentation before applying the code, and also feel free to check other examples on Node File System.
Source: Here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With