I am new to express. I have made a simple react front-end with express backend using express generators and currently, this is the way I am sending JSON data:-
var express = require("express");
var router = express.Router();
router.get("/", function(req, res, next) {
var jsonData = {"name": "manav"};
res.json(jsonData);
});
module.exports = router;
but how can I send data from a JSON file instead? I tried creating a JSON file in the same directory and sending it like res.json('./jsonFile'); but it doesn't work. Could someone help me out please?
You can do like this :
var hoteljsonFile = require("../data/hotel-data.json"); // path of your json file
router.get("/", function(req, res, next) {
res.json(hoteljsonFile);
});
Try in your code like following to read json file
var fs = require('fs');
var path = require('path')
var usersFilePath = path.join(__dirname, 'users.min.json');
apiRouter.get('/users', function(req, res){
var readable = fs.createReadStream(usersFilePath);
readable.pipe(res);
});
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