nodejs reseve json data code example
Example 1: nodejs store json from web api
const http = require("http");
var url = 'https://example.com/file.json';
http.get(url, function(res){
var body = '';
res.on('data', function(chunk){
body += chunk;
});
res.on('end', function(){
var data = JSON.parse(body);
console.log("Got a response: ", data.value);
});
}).on('error', function(e){
console.log("Got an error: ", e);
});
Example 2: nodejs json data serving
const userRoutes = (app, fs) => {
const dataPath = './data/users.json';
app.get('/users', (req, res) => {
fs.readFile(dataPath, 'utf8', (err, data) => {
if (err) {
throw err;
}
res.send(JSON.parse(data));
});
});
};
module.exports = userRoutes;