最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Importing a json file from a url using node js (express) - Stack Overflow

programmeradmin5浏览0评论

I'm a node.js beginner. I'm trying to request a json file from a url (i.e '.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/sample_data.json')

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

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

Share Improve this question asked Apr 24, 2015 at 17:00 Alon WeissfeldAlon Weissfeld 1,3258 gold badges22 silver badges36 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 19

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

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.

发布评论

评论列表(0)

  1. 暂无评论