Importing a json file from a url using node js (express)

12,142

Solution 1

To do that i would use the request module.

var request = require('request');
request('http//exmaple.com/sample_data.json', function (error, response, body) {
  if (!error && response.statusCode == 200) {
     var importedJSON = JSON.parse(body);
     console.log(importedJSON);
  }
})

For more information about the module check this link: https://github.com/request/request

Solution 2

Just some basics about node, and some first things to try:

1) request is a good choice to use for getting the file, but did you do an npm install? "npm install request --save"

2) in order to use the module, you have to "require" it at the top of your code, like: var request = require('request');

I'd start by checking those things first.

Share:
12,142
Alon Weissfeld
Author by

Alon Weissfeld

Updated on July 29, 2022

Comments

  • Alon Weissfeld
    Alon Weissfeld almost 2 years

    I'm a node.js beginner. I'm trying to request a json file from a url (i.e 'http://www.example.com/sample_data.json'). My goal is to download/request the file only once when the server loads and then save it on the client side so I can manipulate/change it locally. I tried

    var file = request('http//exmaple.com/sample_data.json')
    

    but it returns an import module error. If anyone could give me a start that would be great! thanks

  • Jonathan Benn
    Jonathan Benn almost 6 years
    Unfortunately, I have a more complex case (with a proxy and https protocol), and I had to use the https module