gpt4 book ai didi

API Gateway POST 方法在测试期间有效,但不适用于 postman

转载 作者:行者123 更新时间:2023-12-04 15:47:30 25 4
gpt4 key购买 nike

我会尽量清楚地解释我的问题。

我有一个 API,他用 Node.js 编写的 lambda 函数在 DynamoDB 中编写一些东西。当我在 AWS 控制台中调用它时,API 按预期工作。我发送一个这样的 body :

{
"user-id":"4dz545zd",
"name":"Bush",
"firstname":"Gerard",
}

这会在我的 dynamoDB 表中创建条目。但是当我使用 Postman 调用相同的 API(新部署的)时,我收到此错误:
{
"statusCode": "400",
"body": "One or more parameter values were invalid: An AttributeValue may not contain an empty string",
"headers": {
"Content-Type": "application/json"
}
}

当我检查 cloudwatch 失败的原因时,我看到:
转换前的方法请求主体:[二进制数据]

这很奇怪,因为我发送了带有两个 header 的 JSON:
Content-Type:application/json
Accept:application/json

然后在 cloudwatch 中,我看到正在处理的是:
{
"user-id":"",
"name":"",
"firstname":"",
}

这解释了错误,但我不明白为什么当我用 postman 发送它时,它不是空的,使用 json 格式,它仍然将它作为“二进制”数据发送,所以我的映射规则没有处理它(所以 lambda 用一个空的 json 处理它):
#set($inputRoot = $input.path('$'))
{
"httpMethod": "POST",
"body": {
"TableName": "user",
"Item": {
"user-id":"$inputRoot.get('user-id')",
"name":"$inputRoot.get('name')",
"firstname":"$inputRoot.get('firstname')",
}
}
}

先感谢您 !

编辑:我正在添加 lambda 代码函数
'use strict';

console.log('Function Prep');
const doc = require('dynamodb-doc');
const dynamo = new doc.DynamoDB();

exports.handler = (event, context, callback) => {

const done = (err, res) => callback(null, {
statusCode: err ? '400' : '200',
body: err ? err.message : res,
headers: {
'Content-Type': 'application/json'
},
});

switch (event.httpMethod) {
case 'DELETE':
dynamo.deleteItem(event.body, done);
break;
case 'HEAD':
dynamo.getItem(event.body, done);
break;
case 'GET':
if (event.queryStringParameters !== undefined) {
dynamo.scan({ TableName: event.queryStringParameters.TableName }, done);
}
else {
dynamo.getItem(event.body, done);
}
break;
case 'POST':
dynamo.putItem(event.body, done);
break;
case 'PUT':
dynamo.putItem(event.body, done);
break;
default:
done(new Error(`Unsupported method "${event.httpMethod}"`));
}
};

最佳答案

这是因为从 AWS Lambda 的控制台进行测试时,您发送的是您实际期望的 JSON。但是当从 API Gateway 调用它时,事件看起来不同。

您必须访问 event.body 对象才能获得 JSON,但是,主体是字符串化 JSON,这意味着您必须首先解析它。

您没有指定使用哪种语言进行编码,但是如果您使用的是 NodeJS,则可以像这样解析正文:
JSON.parse(event.body)

如果您使用的是 Python,那么您可以这样做:
json.loads(event["body"])
如果您使用任何其他语言,我建议您查看如何从给定的字符串解析 JSON

这给了你所需要的。

这是来自 API Gateway 的事件的样子:

{
"path": "/test/hello",
"headers": {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, lzma, sdch, br",
"Accept-Language": "en-US,en;q=0.8",
"CloudFront-Forwarded-Proto": "https",
"CloudFront-Is-Desktop-Viewer": "true",
"CloudFront-Is-Mobile-Viewer": "false",
"CloudFront-Is-SmartTV-Viewer": "false",
"CloudFront-Is-Tablet-Viewer": "false",
"CloudFront-Viewer-Country": "US",
"Host": "wt6mne2s9k.execute-api.us-west-2.amazonaws.com",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 OPR/39.0.2256.48",
"Via": "1.1 fb7cca60f0ecd82ce07790c9c5eef16c.cloudfront.net (CloudFront)",
"X-Amz-Cf-Id": "nBsWBOrSHMgnaROZJK1wGCZ9PcRcSpq_oSXZNQwQ10OTZL4cimZo3g==",
"X-Forwarded-For": "192.168.100.1, 192.168.1.1",
"X-Forwarded-Port": "443",
"X-Forwarded-Proto": "https"
},
"pathParameters": {
"proxy": "hello"
},
"requestContext": {
"accountId": "123456789012",
"resourceId": "us4z18",
"stage": "test",
"requestId": "41b45ea3-70b5-11e6-b7bd-69b5aaebc7d9",
"identity": {
"cognitoIdentityPoolId": "",
"accountId": "",
"cognitoIdentityId": "",
"caller": "",
"apiKey": "",
"sourceIp": "192.168.100.1",
"cognitoAuthenticationType": "",
"cognitoAuthenticationProvider": "",
"userArn": "",
"userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 OPR/39.0.2256.48",
"user": ""
},
"resourcePath": "/{proxy+}",
"httpMethod": "GET",
"apiId": "wt6mne2s9k"
},
"resource": "/{proxy+}",
"httpMethod": "GET",
"queryStringParameters": {
"name": "me"
},
"stageVariables": {
"stageVarName": "stageVarValue"
},
"body": "'{\"user-id\":\"123\",\"name\":\"name\", \"firstname\":\"firstname\"}'"
}

编辑

在评论中进一步讨论之后,还有一个问题是您使用的是 DynamoDB API 而不是 DocumentClient API。使用 DynamoDB API 时,您必须指定对象的类型。另一方面,DocumentClient 将这种复杂性抽象化了。

我还稍微重构了您的代码(为了简单起见,目前仅处理 POST),因此您可以使用 async/await
'use strict';

console.log('Function Prep');
const AWS = require('aws-sdk');
const dynamo = new AWS.DynamoDB.DocumentClient();

exports.handler = async (event) => {

switch (event.httpMethod) {
case 'POST':
await dynamo.put({TableName: 'users', Item: JSON.parse(event.body)}).promise();
break;
default:
throw new Error(`Unsupported method "${event.httpMethod}"`);
}
return {
statusCode: 200,
body: JSON.stringify({message: 'Success'})
}
};

这是 DynamoDB 中的项目:

enter image description here

这是我的 postman 要求:

enter image description here

使用适当的标题:

enter image description here

创建 API 网关时,我选中了 Use Lambda Proxy integration 框。我的 API 看起来像这样:

enter image description here

如果您重现这些步骤,它应该可以正常工作。

关于API Gateway POST 方法在测试期间有效,但不适用于 postman ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55354065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com