Node.js 12.x环境下Lambda调用POST API的实现、参数传递与报错解决
Lambda Node.js 12.x 环境下POST API调用问题梳理
初始实现代码
在Node.js 12.x运行时的Lambda函数中,最初的POST调用实现直接依赖第三方request模块,代码内容如下:
var posturl = "My post api path"; var jsonData = "{'password':'abcdef','domain':'www.mydomain.com','username':'abc.def'}"; var req = require('request'); const params = { url: posturl, headers: { 'jsonData': jsonData } }; req.post(params, function(err, res, body) { if(err){ console.log('------error------', err); } else{ console.log('------success--------', body); } });
运行异常
通过Step Functions状态机触发Lambda执行时,返回的错误信息如下:
{ "errorType": "Error", "errorMessage": "Cannot find module 'request'\nRequire stack:\n- /var/task/index.js\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js", "trace": [ "Error: Cannot find module 'request'", "Require stack:", "- /var/task/index.js", "- /var/runtime/UserFunction.js", "- /var/runtime/index.js", " at Function.Module._resolveFilename (internal/modules/cjs/loader.js:815:15)", " at Function.Module._load (internal/modules/cjs/loader.js:667:27)", " at Module.require (internal/modules/cjs/loader.js:887:19)", " at require (internal/modules/cjs/helpers.js:74:18)", " at Runtime.exports.handler (/var/task/index.js:8:14)", " at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)" ] }
核心待解决问题
- 如何在Lambda函数中正确发起POST API调用
- 接口要求必须通过
jsonData键传递完整业务数据,缺少该字段接口将无法正常响应,如何在调用时正确构造传递参数 - 服务调用完成后,如何正确解析接口返回的响应内容
调整后的尝试实现
后续为了绕开第三方模块加载问题,改用Node.js内置http模块实现调用,对应代码如下:
exports.handler = (event, context, callback) => { const http = require('http'); const data = JSON.stringify({ password: 'mypassword', domain: 'www.mydomain.com', username: 'myusername' }); const options = { hostname: 'http://abc.mydomain.com', path: 'remaining path with ticket', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': data.length } }; const req = http.request(options, (res) => { let resData = ''; console.log('Status Code:', res.statusCode); res.on('data', (chunk) => { resData += chunk; }); res.on('end', () => { console.log('Body: ', JSON.parse(resData)); }); }).on("error", (err) => { console.log("Error: ", err.message); }); req.write(data); req.end(); };
注:该实现暂未按接口要求在请求头中携带
jsonData字段
内容的提问来源于stack exchange,提问作者Matthew Pans
相关产品推荐
相关产品推荐

