'Express: sending JSON file as a response
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?
Solution 1:[1]
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);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | minimalpop |
