Javascript 在Express中使用URL中的JSON
问题是:如何从URL(而不是Express中的内部文件)导入json,并将其包含在多个视图中使用。例如,我有一个控制器。我怎样才能进去(管制员)?我正在使用Javascript 在Express中使用URL中的JSON,javascript,json,node.js,express,Javascript,Json,Node.js,Express,问题是:如何从URL(而不是Express中的内部文件)导入json,并将其包含在多个视图中使用。例如,我有一个控制器。我怎样才能进去(管制员)?我正在使用请求 我有一个有两条路由的路由器,但我想有更多的路由,路由的大部分逻辑都是在控制器中完成的 下面是一个控制器,其路线用于显示所有。我在其中硬编码了一小段“json”作为临时使用的数据,但现在我想通过外部api填充我的视图。这是我的控制器: module.exports = { //show all USERS showDogs: (req,
请求
我有一个有两条路由的路由器,但我想有更多的路由,路由的大部分逻辑都是在控制器中完成的
下面是一个控制器,其路线用于显示所有。我在其中硬编码了一小段“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
中,否则其他函数将无法访问它。对吗?
我在下面有类似的东西,在控制器的顶部有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
}
我还尝试在请求中包装整个内容和所有函数:
request('https://raw.githubusercontent.com/matteocrippa/dogbreedjsondatabase/master/dog-breed.json', function(error, response, body)
但我还是犯了一个错误
这是route.js,控制器在其中发送:
//dogs
router.get('/dogs', dogsController.showDogs)
我是一个节点初学者,所以我唯一的想法就是编写一些中间件。这里更深层次的问题是我不知道如何正确地使用/编写中间件。也许我可以得到通知。添加一个实用程序文件,其中包含与外部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
}
});
}