[英]How to send post request to external api in aws lambda with nodejs 10x?
I am trying to send post request to an external api in aws lambda using nodejs 10.x. 我正在尝试使用nodejs 10.x将发布请求发送到AWS Lambda中的外部api。 But I am getting error
但是我出错了
Response:
{
"errorMessage": "Converting circular structure to JSON",
"errorType": "TypeError",
"stackTrace": []
}
Please find the code below: 请在下面找到代码:
const http = require('https');
exports.handler = async (event) => {
return new Promise((resolve, reject) => {
const req = http.request('https://jsonplaceholder.typicode.com/posts', (res) => {
resolve(res);
});
req.on('error', (e) => {
reject({error: e.message});
});
// send the request
req.write('');
req.end();
});
};
I am expecting json response like below 我期待如下的json响应
[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
}
]
You are using http.request
without adding options object but a URL. 您正在使用
http.request
而不添加选项对象,但添加URL。 You should replace it with http.get
or add options object. 您应该将其替换为
http.get
或添加选项对象。
You are also resolving response from http request without building the data. 您还将解决http请求的响应,而无需构建数据。 If you are using Lambda behind API Gateway proxy integration then response should be formatted.
如果在API网关代理集成之后使用Lambda,则应格式化响应。 Following code should work.
下面的代码应该工作。
const http = require('https');
let getData = () => {
return new Promise((resolve, reject) => {
http.get('https://jsonplaceholder.typicode.com/posts', (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
resolve(data);
});
}).on('error', (e) => {
console.log('Error', e.message);
reject(e);
});
});
};
module.exports.handler = async (event) => {
try {
// Data is string.
const data = await getData();
return {
statusCode: 200,
body: data
}
}
catch (e) {
console.log(e);
return {
statusCode: 400,
body: e.message
}
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.