Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express: sending JSON file as a response

Tags:

json

express

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?

like image 729
Manav Saxena Avatar asked Aug 16 '17 06:08

Manav Saxena


2 Answers

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);
});
like image 135
jANVI Avatar answered Oct 31 '22 06:10

jANVI


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);
});
like image 36
Prabhakaran Ravichandran Avatar answered Oct 31 '22 06:10

Prabhakaran Ravichandran