13

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?

Person
  • 2,190
  • 7
  • 30
  • 58

2 Answers2

21

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

Vipin Yadav
  • 1,616
  • 1
  • 14
  • 23
1

You can create a local rest server and return json format saved in one file by :

File app.js

'use strict'

var http = require('http');
var url = require('url');
var fs = require('fs');
var path = require('path');

http.createServer((request, response) => {
  let urlInfo = url.parse(request.url, true); // host, pathname, search
  let method = request.method;

  if (method == 'GET') {
   console.log(urlInfo.pathname);
  if (urlInfo.pathname.includes('request1') ) {
  sendResponse('./request1.txt',response)

    } 
  } else {
    sendResponse("", "")
  }
}).listen(3000,"192.168.0.1");       // change your local host here
console.log("Start server at port 3000");

function sendResponse(filename,response) {
 var sampleTxt = path.join(__dirname, filename);
 console.log(filename);
 fs.readFile(sampleTxt, function(error, data) {
   if (error) return console.error(error);
  response.writeHead(200, {'Content-Type': 'application/json;charset=UTF-8', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST, GET, PUT, DELETE, OPTIONS', "Access-Control-Allow-Headers": "If-Modified-Since"});
     response.write(data);
  response.end();
   
 });
}

In file request1.txt => save response format as you want

[
  {
    "uuid": "id1",
    "userId": 80778,
    "mac": "mac1",
    "name": "Living & Dining Room"
  },
  {
    "uuid": "id2",
    "userId": 80778,
    "mac": "mac2",
    "name": "Bed Room"
  },
  {
    "uuid": "id3",
    "userId": 80778,
    "mac": "mac3",
    "name": "Kitchen"
  }
]

Run app.js

vuhoanghiep1993
  • 715
  • 1
  • 8
  • 15