Rag*_*ull 4 amazon-web-services node.js aws-lambda aws-api-gateway
这是aws lambda函数,它将调用一个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)
}
})
};
Run Code Online (Sandbox Code Playgroud)
这是写为aws lambda函数的api:
'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
};
Run Code Online (Sandbox Code Playgroud)
当我尝试从lambda函数调用api时,它仅返回“ Hello World undefined”。它不会在名称末尾附加名称并返回正确的响应。
假设:
您误会了什么event。这不是您通过HTTP请求发送的JSON有效负载。
通过API网关的HTTP请求被转换为event类似于以下内容的对象:
{
"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"
}
Run Code Online (Sandbox Code Playgroud)
如您所见,JSON有效负载可以在中以字符串形式访问event.body。
如果要将相同的有效载荷发送给第二个Lambda,则必须首先对其进行解析。
const body = JSON.parse(event.body)
Run Code Online (Sandbox Code Playgroud)
然后,发送body而不是event。
然后,在第二个Lambda中,解析入字符串化的JSON event.body,然后取回原始有效负载。
如果您发送name的是原始有效负载,则可以从获取JSON.parse(event.body).name。
参考:http : //docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html#api-gateway-simple-proxy-for-lambda-input-format
| 归档时间: |
|
| 查看次数: |
4746 次 |
| 最近记录: |