在Express中使用来自URL的JSON

问题是:如何从一个URL中专门导入json,而不是Express中的内部文件,并且包含它,以便我可以在多个视图中使用它。 例如,我有一个控制器。 我怎样才能进去(控制器)? 我正在使用request

我有一个路由器与2路由,但我想有更多的一堆,而路由的逻辑大部分正在控制器中完成。

下面是一个显示所有路线的控制器。 我已经硬编码了一小块“json”作为临时使用的数据,但现在我想通过外部api填充我的视图。 这是我的控制者:

 module.exports = { //show all USERS showDogs: (req,res) => { const dogs = [ { name:"Fluffy", breed:"ChowChow", slug:"fluffy", description:"4 year old Chow. Really, really fluffy." }, { name:"Buddy", breed:"White Lab", slug:"buddy", description:"A friendly 6 year old white lab mix. Loves playing ball" }, { name: "Derbis", breed:"Schmerbis",slug:"derbis", description:"A real Schmerbis Derbis" } ]; res.render("pages/dogs", {dogs: dogs, title:"All Dogs"}); } }; 

我怎样才能得到这个json的数据来自外线? 我以前使用过request ,但是我不知道如何在文件之间传输数据。 我不想把它放在showDogs里面,否则这个function将无法使用。 对? 我有这样的下面的东西,在控制器的顶部require('request') ,但它只是给了错误。

  const options = { url:'https://raw.githubusercontent.com/matteocrippa/dogbreedjsondatabase/master/dog-breed.json', method:'GET', headers:{ 'Accept-Charset': "utf-8" NO IDEA ABOUT THIS AREA FOR NOW EITHER } 

我也尝试在请求中包装整个东西,所有的function:

 request('https://raw.githubusercontent.com/matteocrippa/dogbreedjsondatabase/master/dog-breed.json', function(error, response, body) 

但是我仍然有一个错误。

而这是控制器发送的route.js:

  //dogs router.get('/dogs', dogsController.showDogs) 

我是Node初学者,所以我唯一的想法就是写一些中间件。 这里更深层次的问题是我不知道如何正确使用/编写中间件。 也许我可以变得知情。

添加一个实用程序文件,其中包含与外部API交谈的代码。 包括这个文件,并使用它的function来获取狗的数据。 稍后,您还可以为其他API添加更多function。

  const getDogData = require('../externalApis').getDogData; module.exports = { //show all USERS showDogs: (req, res) => { getDogData(function(err, dogs) { if (err) { //handle err } else { res.render("pages/dogs", { dogs: dogs, title: "All Dogs" }); } } } }; // externalApis.js const request = require ('request'); module.exports = { getDogData: function(done) { const options = { url: 'https://raw.githubusercontent.com/matteocrippa/dogbreedjsondatabase/master/dog-breed.json', method: 'GET', headers: { 'Accept-Charset': "utf-8" } } request(options, function(error, response, body) { if (error) { return done(err); } else { var data = JSON.parse(body); // not sure how's data is returned or if it needs JSON.parse return done(null, data.dogs); //return dogs } }); }