我正在尝试将AWS Lambda中的request模块用于Node.js,但效果不佳。
这是我到目前为止拥有的功能:
const request = require('request');
url = 'https://www.google.com'
exports.handler = async (event) => {
request(url, (error,res,body) => {
console.log(error); //this is not printing
console.log(res); //this is not printing
console.log(body); //this is not printing
console.log('Come on!!'); //this is not printing
});
console.log(url); //This is the only thing printing, you can see in the Function Logs below, second line.
};
这是我得到的回应:
Response:
null
Request ID:
"3e46f401-f26d-435d-90be-ac848c6c3a39"
Function Logs:
START RequestId: 3e46f401-f26d-435d-90be-ac848c6c3a39 Version: $LATEST
2019-10-14T08:06:23.755Z 3e46f401-f26d-435d-90be-ac848c6c3a39 INFO https://www.google.com
END RequestId: 3e46f401-f26d-435d-90be-ac848c6c3a39
REPORT RequestId: 3e46f401-f26d-435d-90be-ac848c6c3a39 Duration: 368.93 ms Billed Duration: 400 ms Memory Size: 128 MB Max Memory Used: 92 MB Init Duration: 461.54 ms
我想知道为什么我没有从requests方法中得到任何响应。我在笔记本电脑上尝试过,并且处理程序外部的部分代码工作正常。
我将项目作为zip文件上传,因此带有请求模块的node_modules文件夹确实存在。我注意到使用http模块而不是request的一些解决方案,但是我想先了解为什么它不起作用,然后再转向其他解决方案。
您的函数被标记为async
,但是您正在使用回调来处理响应。所以什么都没有awaited
发生。
这意味着您的函数将返回一个已兑现的隐含承诺。这使lambda停止。因此,要么:
A)使用async / await编写您的代码,这可能需要request-promise
或类似的方法:
exports.handler = async event => {
const res = await promisifiedRequest(url);
console.log(res.statusCode);
console.log(url);
};
要么
B)将函数从转换async/await
为使用回调,如下所示:
exports.handler = (event, context, callback) => {
const res = request(url, (error, res, body) => {
console.log('Come on!!');
callback(null, res.statusCode);
});
console.log(url);
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句