我正在尝试从服务器端(.js)的REST API检索数据并将其显示在我的视图( .jade)中
我能够获取数据,但无法将其发送到视图。这是我的代码的样子:
var BugData ='initial data' ;
var https = require('https');
var optionsget = {
rejectUnauthorized: false,
host : 'My host', // here only the domain name
// (no http/https !)
port : 443,
path : 'Mypath', // the rest of the url with parameters if needed
method : 'GET' // do GET
};
console.info('Options prepared:');
console.info(optionsget);
console.info('Do the GET call');
// do the GET request
var reqGet = https.request(optionsget, function(res) {
console.log("statusCode: ", res.statusCode);
res.on('data', function(d) {
console.info('GET result:\n');
BugData =d;
console.log('Show Data : ***** \n' +d);
});
});
reqGet.end();
reqGet.on('error', function(e) {
console.error(e);
});
res.render('index', { ab:BugData});
BugData(在之前定义)是我试图发送给视图的变量,但是由于某些原因,它为空并且不包含变量“ d”
有谁知道为什么或如何解决这个问题?谢谢
无需编写那么长的代码。
很简单,请按照下列步骤操作:
1)安装请求包:
npm install --save request
2)在路由器外添加:
var request = require('request');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
3)在路由器内部使用此代码:
request.get({url: 'https://my-host/Mypath'}, function(err, response, body) {
var data = {};
if (err) {
console.error(err);
data.err = err;
}
data.ab = body;
console.log('Data: ', data);
res.render('index', data);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句