从Express中的URL使用JSON

时间:2017-03-26 19:46:54

标签: javascript json node.js express

问题是:如何从URL专门导入json,而不是Express中的内部文件,并包含它以便我可以在多个视图中使用它。例如,我有一个控制器。我怎样才能进入(控制器)?我正在使用docker cp file.txt <container-name>:/path/to/directory

我有一个带2条路由的路由器,但我想要更多,路由的大部分逻辑都是在控制器中完成的。

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

request

如何让这个json数据来自外线?我之前使用过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"}); } }; ,但我不知道如何在文件之间传输数据。我不想把它放在request里面,或者这里的其他功能无法访问它。对? 我在下面有这样的东西,控制器顶部有showDogs,但它只是出错了。

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
  }

但我仍然有错误。

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

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

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

1 个答案:

答案 0 :(得分:0)

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

   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
                   }

               });

           }