Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make GET request with express.js to a local json file?

I want to make a GET request to a local JSON file with express.

In my server.js I have this

var data = {};
app.get('/src/assets/data.json', (req, res) => {
  console.log(res)
  res.writeHead(200, {
    'Content-type': 'application/json'
  });

  res.end(JSON.stringify(data));
});

data.json looks like this

[{
    "param": "one",
    "param": "two",
    "param": "three"
  }]

Also I made a function for GET request which is called as soon as the DOM is loaded

getData() {
    let xhr = new XMLHttpRequest();
    xhr.open('GET', '/src/assets/data.json', true);
    xhr.onreadystatechange = () => {
      if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
        console.log(xhr)
      }
    };
    xhr.send();
  }

I'm getting a response back but it is an empty object. I'm guessing it is because in my server file var data = {}; is empty but I'm not sure what to do with it?

like image 673
Person Avatar asked Nov 11 '17 10:11

Person


People also ask

How do I get a body from Express request?

Express has a built-in express. json() function that returns an Express middleware function that parses JSON HTTP request bodies into JavaScript objects. The json() middleware adds a body property to the Express request req . To access the parsed request body, use req.


1 Answers

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

  1. Read the data.json file.
  2. 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

like image 160
Vipin Yadav Avatar answered Sep 21 '22 06:09

Vipin Yadav