我将 sailsjs 用作 Node js 的 MVC,我仍在学习它。 我设法从我自己的数据库中获取数据并使用它。
但现在我需要/想要从外部 rest api 获取数据。 我在我的 Controller 中使用了这个:
// api/controllers/SomeController.js
test : function(res,req){
var j;
var https = require('https');
var options = {
hostname: 'testing.atlassian.net',
port: 443,
path: '/rest/api/2/search?jql=project=ABC',
method: 'GET',
headers: {'Authorization': 'Basic ' + 'SuperSecretLoginAndPassword'}
};
var req = https.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function(d) {
});
});
req.end();
}
变量 d
显示正确的结果。
我如何在我的 View 中使用请求结果?
我搜索了很多,但找不到任何方法在我的 View 中显示它。
这会实时更新吗?因此,如果 de rest api 中的某些内容发生变化,我将不必刷新。
抱歉,如果这是愚蠢的事情。
最佳答案
基本上,您需要等待您的请求触发其回调,然后将获取的数据提供给 res.locals
。假设您正在获取 JSON 数据,您可以这样做:
// api/controllers/SomeController.js
test: function(req, res) {
var https = require('https');
...
https.request(options, function(response) {
var responseData = '';
response.setEncoding('utf8');
response.on('data', function(chunk){
responseData += chunk;
});
response.once('error', function(err){
// Some error handling here, e.g.:
res.serverError(err);
});
response.on('end', function(){
try {
// response available as `responseData` in `yourview`
res.locals.requestData = JSON.parse(responseData);
} catch (e) {
sails.log.warn('Could not parse response from options.hostname: ' + e);
}
res.view('yourview');
});
}).end();
}
您提供的示例代码存在一些问题:
test: function(res,req) ...
不要混淆 Controller 参数,第一个是 _req_uest,第二个是 _res_ponse。var req = https.request ...
您真的不想覆盖传递给 Controller 操作的req
参数。使用其他名称。https.request(options, function(res) {...}
同样在这里。这样做会覆盖https.request 的
回调范围 - 阻止您使用传递给 Controller 的res
res
参数提供的所有好东西(例如:res.view
)。
我猜你阅读闭包和回调会很有意义:
关于javascript - 如何在 Sails js (nodejs MVC) 中使用外部 rest api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21757848/