Nodejs API调用返回未定义的lambda函数
这是将调用api的aws lambda函数:
This is the aws lambda function which will invoke an api:
'use strict';
var request = require("request")
exports.handler = function (event, context,callback) {
let url = "https://3sawt0jvzf.execute-api.us-east-1.amazonaws.com/prod/test"
request({
url: url,
method: "POST",
json: event,
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
callback(null, { "isBase64Encoded": true|false,
"statusCode": "200",
"headers": { "headerName": "headerValue"},
"body": body});
}
else {
console.log("error: " + error)
console.log("response.statusCode: " + response.statusCode)
console.log("response.statusText: " + response.statusText)
}
})
};
这是写为aws lambda函数的api:
This is the api written as an aws lambda function:
'use strict';
exports.handler = function(event, context, callback) {
console.log(event.name);
callback(null, { "isBase64Encoded": true|false,
"statusCode": "200",
"headers": { "headerName": "headerValue"},
"body": `Hello World ${event.name}`}); // SUCCESS with message
};
当我尝试从lambda函数调用api时,它仅返回"Hello World undefined".它没有在名称末尾附加名称并返回正确的响应.
When I try to call the api from the lambda function it just returns "Hello World undefined". It is not appending the name at the end and returning the correct response.
假设:
- 您正在使用Lambda-Proxy集成.
- 您想将与第一个Lambda完全相同的有效负载传递给第二个Lambda.*
您误解了event
是什么.这不是您通过HTTP请求发送的JSON有效负载.
You're misunderstanding what event
is. This is NOT the JSON payload that you sent through your HTTP request.
通过API网关的HTTP请求被转换为类似于以下内容的event
对象:
An HTTP request through the API Gateway gets transformed into an event
object similar to this:
{
"resource": "Resource path",
"path": "Path parameter",
"httpMethod": "Incoming request's method name"
"headers": {Incoming request headers}
"queryStringParameters": {query string parameters }
"pathParameters": {path parameters}
"stageVariables": {Applicable stage variables}
"requestContext": {Request context, including authorizer-returned key-value pairs}
"body": "A JSON string of the request payload."
"isBase64Encoded": "A boolean flag to indicate if the applicable request payload is Base64-encode"
}
如您所见,可以在event.body
中以字符串形式访问JSON有效负载.
As you can see, the JSON payload is accessible in a stringified form in event.body
.
如果要将相同的有效载荷发送给第二个Lambda,则必须先对其进行解析.
If you want to send the pass the same payload to the second Lambda, you have to parse it first.
const body = JSON.parse(event.body)
然后,发送body
而不是event
.
然后,在第二个Lambda中,解析event.body
中的字符串化JSON,然后取回原始有效负载.
Then, in your second Lambda, you parse the stringified JSON in event.body
and then you get your original payload back.
如果您在原始有效载荷中发送了name
,则可以从JSON.parse(event.body).name
获取它.
If you sent name
in that original payload, you can get it from JSON.parse(event.body).name
.
参考: 查看更多