How to make GET request with express.js to a local json file?
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
- Read the
data.json
file. - Put all data from the file into object i.e.
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
You can create a local rest server and return json format saved in one file by :
File app.js
'use strict'
var http = require('http');
var url = require('url');
var fs = require('fs');
var path = require('path');
http.createServer((request, response) => {
let urlInfo = url.parse(request.url, true); // host, pathname, search
let method = request.method;
if (method == 'GET') {
console.log(urlInfo.pathname);
if (urlInfo.pathname.includes('request1') ) {
sendResponse('./request1.txt',response)
}
} else {
sendResponse("", "")
}
}).listen(3000,"192.168.0.1"); // change your local host here
console.log("Start server at port 3000");
function sendResponse(filename,response) {
var sampleTxt = path.join(__dirname, filename);
console.log(filename);
fs.readFile(sampleTxt, function(error, data) {
if (error) return console.error(error);
response.writeHead(200, {'Content-Type': 'application/json;charset=UTF-8', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST, GET, PUT, DELETE, OPTIONS', "Access-Control-Allow-Headers": "If-Modified-Since"});
response.write(data);
response.end();
});
}
In file request1.txt => save response format as you want
[
{
"uuid": "id1",
"userId": 80778,
"mac": "mac1",
"name": "Living & Dining Room"
},
{
"uuid": "id2",
"userId": 80778,
"mac": "mac2",
"name": "Bed Room"
},
{
"uuid": "id3",
"userId": 80778,
"mac": "mac3",
"name": "Kitchen"
}
]
Run app.js