gpt4 book ai didi

node.js - 获取 NodeJS 的 Http 响应

转载 作者:太空宇宙 更新时间:2023-11-03 22:49:07 25 4
gpt4 key购买 nike

尝试在 NodeJS(nodeJs 新手)中执行 AWS Lambda,并在其中发出 http 请求。在Lambda执行结束时,我希望返回http请求的响应代码和响应消息。

进行http请求调用:

var executeRequest = function(request, callback) {

const req = https.request(request, (res) => {

console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);

res.on('data', (d) => {
process.stdout.write(d);
});
callback(res);
});

req.on('error', (e) => {
console.error(e);
});

req.end(request.body);

};

Lambda代码:

    exports.handler = (event, context, callback) => {

// Formulate request

var result = executeRequest(request, function(response) {
console.log("Response Code: ", response.statusCode);
console.log("Response Message: ", response.statusMessage);
// Successfully able to print the response above

return response;
});
console.log("Result Response Code: ", result);
console.log("Result Response Message: ", result);
}

我希望返回response.statusCode和response.statusMessage作为来自Lambda的响应

return{
statusCode: <the code>,
body: <the message>,
};

但是,结果被填充为未定义。如何提取所需的响应参数以便正确返回?

** 编辑:**建议更改后的片段: 使用 Promise 的代码:

var executeRequest = function(request, callback) {

return new Promise((resolve, reject) => {
https.request(request, function(res) {
if(res.statusCode==200 || res.statusCode==404) {
resolve(res);
}
else {
console.error(res);
reject(res.statusCode);
}
}).end(request.body || '');
});
};


exports.handler = (event, context, callback) => {

// Formulate request

var value = executeRequest(request).then(function(result) {
console.log("Result ", result);
const response = { statusCode: 200, body: JSON.stringify('Hello from Lambda!') };
return response;
});

console.log(value);
}

最佳答案

问题是您的 executeRequest 是异步的,而您的 lambda 不知道这一点,因此它只会立即返回。

不返回响应,而是将其作为第二个参数传递给回调(第一个是错误对象)

callback(null, response)

这部分执行完毕,无需等待 executeRequest 响应,其余代码就会执行

var result = executeRequest(request, function(response) {
console.log("Response Code: ", response.statusCode);
console.log("Response Message: ", response.statusMessage);
// Successfully able to print the response above

return response;
});

所以此时

console.log("Result Response Code: ", result);
console.log("Result Response Message: ", result);

结果仍然为空。

所以你应该做这样的事情。

var result = executeRequest(request, function(response) {
console.log("Response Code: ", response.statusCode);
console.log("Response Message: ", response.statusMessage);
// Successfully able to print the response above

callback(null, response);
});

关于node.js - 获取 NodeJS 的 Http 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56282565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com