我有一个NodeJS API。 API中的逻辑需要向google.com发出http get请求,从google.com捕获响应,然后将html响应返回到原始API调用。我的问题是从谷歌异步捕获http响应并将其返回到原始API调用。
// Entry point to /api/specialday
module.exports = function(apiReq, apiRes, apiNext) {
var options = {
host: 'www.google.com'
};
callback = function(googleRes) {
var str = '';
// another chunk of data has been recieved, so append it to `str`
googleRes.on('data', function (chunk) {
str += chunk;
});
// capture the google response and relay it to the original api call.
googleRes.on('end', function () {
apiRes.send(str);
});
}
http.request(options, callback).end();
}
我在这里遇到的错误是Uncaught TypeError: Cannot read property 'send' of undefined
。我理解为什么我得到错误(因为apiRes超出范围),我只是无法弄清楚如何正确地做到这一点。任何帮助非常感谢!
答案 0 :(得分:0)
您看到上述错误的原因是,当您收到Google API的响应时,原始响应对象apiRes
已消失。
据我所知,你必须bind()
apiRes
两次(未经测试):
callback = function(googleRes) {
var str = '';
// another chunk of data has been recieved, so append it to `str`
googleRes.on('data', function (chunk) {
str += chunk;
});
// capture the google response and relay it to the original api call.
googleRes.on('end', function () {
apiRes.send(str);
}.bind(apiRes));
}.bind(apiRes)
更现代的解决方案是使用此任务的承诺https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
答案 1 :(得分:0)
承诺,就是这样!谢谢Michal。以下是我的实施的简化版本。
// Entry point to /api/specialday
module.exports = function(apiReq, apiRes, apiNext) {
var p1 = new Promise(
// The resolver function is called with the ability to resolve or
// reject the promise
function(resolve, reject) {
var options = {
host: 'www.google.com'
};
callback = function(googleRes) {
var str = '';
// another chunk of data has been recieved, so append it to `str`
googleRes.on('data', function (chunk) {
str += chunk;
});
// capture the google response and relay it to the original api call.
googleRes.on('end', function () {
resolve(str);
});
}
http.request(options, callback).end();
)};
p1.then(function(googleHtml) {
apiRes.status(200).send(googleHtml);
}
}
然后我可以运行我的应用程序并使用Postman在http://localhost:8080/api/gains
:
答案 2 :(得分:0)
使用apiRes直接输出管道,使用请求样本:
var request = require("request");
// Entry point to /api/specialday
module.exports = function(apiReq, apiRes, apiNext) {
request.get('http://www.google.fr').pipe(apiRes);
});