6

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?

Manav Saxena
  • 453
  • 2
  • 8
  • 21

2 Answers2

11

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);
});
jANVI
  • 718
  • 3
  • 12
  • This works, but what if the data in the JSON file changes? Even if I put the require statement in the function, it will be executed only once and store the object in cache until the express server reloads. – sarius Apr 13 '23 at 14:56
  • https://stackoverflow.com/a/51655919/17330227 Here is the solution for my above mentioned problem. – sarius Apr 13 '23 at 15:08
4

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);
});
minimalpop
  • 6,997
  • 13
  • 68
  • 80
  • This is a better answer imho – Taylor Ackley Jun 05 '20 at 23:15
  • 1
    But this just sends the text, it doesn't send the data AS JSON, even if you set `Content-Type: application/json`. How do you send it as JSON, not text? – user1944491 Apr 14 '21 at 12:51
  • 1
    @user1944491 JSON is text. This is why the method to create json is called "stringify". – Mig Jun 29 '22 at 10:02
  • 1
    @Mig JSON is text, but it has a structure and required delimiters. – user1944491 Jun 30 '22 at 15:02
  • @user1944491 Yes but the Content-Type is the only thing that differentiate text from JSON. Or identifies it as JSON if you will. So I don't understand your comment. The sending is probably not the problem. As soon as you have the proper content type, it is the client's responsibility to read the content type and parse accordingly. Most browsers do this automatically. And if you build an API, then it has to check the content type and parse. There is no such thing as "sending JSON" per se. All you can do is make sure it is well formatted to be parsed. – Mig Sep 27 '22 at 08:36
  • @Mig "All you can do is make sure it is well formatted to be parsed." -- that's exactly what I've been saying. – user1944491 Nov 12 '22 at 03:38