我想在我的 AWS Lambda 函数中返回 HTTP 请求的结果:
var http = require('http');
exports.someFunction = function(event, context) {
var url = "http://router.project-osrm.org/trip?loc=47.95,12.95&loc=47.94,12.94";
http.get(url, function(res) {
context.succeed(res);
}).on('error', function(e) {
context.fail("Got error: " + e.message);
});
}
它应该准确地返回当我直接在浏览器中打开 url 时得到的内容(尝试查看预期的 json)。
当我调用 context.succeed(res)
时,AWS Lambda 返回以下错误消息:
{
"errorMessage": "Unable to stringify body as json: Converting circular structure to JSON",
"errorType": "TypeError"
}
我假设我需要使用 res
的某些属性而不是 res
本身,但我无法弄清楚哪个属性包含我想要的实际数据。
最佳答案
如果您使用原始 http
模块,则需要监听 data
和 end
事件。
exports.someFunction = function(event, context) {
var url = "http://router.project-osrm.org/trip?loc=47.95,12.95&loc=47.94,12.94";
http.get(url, function(res) {
// Continuously update stream with data
var body = '';
res.on('data', function(d) {
body += d;
});
res.on('end', function() {
context.succeed(body);
});
res.on('error', function(e) {
context.fail("Got error: " + e.message);
});
});
}
使用另一个模块,例如request
https://www.npmjs.com/package/request这样您就不必管理这些事件,并且您的代码几乎可以恢复到以前的状态。
关于json - AWS Lambda http请求: Unable to stringify body as json: Converting circular structure to JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35276297/