【发布时间】:2021-06-09 19:28:25
【问题描述】:
我在 AWS 中编写了一个 lambda 函数,它从 Dynamo DB 中获取数据并以 JSON 格式返回。它采用格式 - {"Datestamp":"2021-01-11"} 的请求输入正文并返回此日期的报告。
我正在使用 java 脚本从网页调用它,但出现“无法编组响应”错误。
Javascript 代码 -
$.ajax({
type : "POST",
contentType : "application/json",
url : "https://mypoc-app.com/api/",
data:
{
"Datestamp" : "2021-02-15"
},
headers: {
'Authorization': 'Basic',
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
'Access-Control-Allow-Methods': 'DELETE, POST, GET, OPTIONS',
'Access-Control-Allow-Credentials' : true
//'Access-Control-Allow-Headers': 'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With',
},
dataType : "json",
success : function(data,status) {
console.log("Date format is " + data);
if (response != null)
{
drawTable(response.data);
}
},
error: function () {
console.log("Error");
}
});
Lambda 函数 -
def lambda_handler(event, context):
try:
result = []
queryresponse = resultstable.scan()
for i in queryresponse['Items']:
result.append(i['reports'])
block=['{"type": "section","text": {"type": "mrkdwn","text": "*Found below reports using Datestamp provided*"}}']
for item in result:
print(event["body"])
body = json.loads(event["body"])
if item.find(body['Datestamp']) != -1:
itema='{"type": "section","text": {"type": "mrkdwn","text": "<https://%s/%s/%s/index.html|%s>"}}' % (URL,Prefix,item,item)
block.append(itema)
block=('[{}]'.format(', '.join(block)))
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
'body': block,
"isBase64Encoded": False
}
except Exception as e:
print(e)
return(e)
Cloudwatch 中的错误日志 -
START RequestId: XXXXXXXXXXXXXXXXXXXX Version: $LATEST
Datestamp=2021-02-15
Expecting value: line 1 column 1 (char 0)
[ERROR] Runtime.MarshalError: Unable to marshal response: JSONDecodeError('Expecting value: line 1 column 1 (char 0)') is not JSON serializable
END XXXXXXXXXXXXXXXXXXXX
我认为这与我在请求中传递日期的方式或 lambda 处理它的方式有关,因为从云观察日志来看,它看起来不像是 JSON 格式。
有人可以提供他们在这种情况下的专业知识吗,因为我已经摸不着头脑了?
【问题讨论】:
-
您能否在 Lambda 控制台中成功运行此 Lambda 函数?
-
@smac2020 是的,它可以在 AWS 控制台上正常工作,甚至可以使用邮递员。我像这样在请求正文中传递
datestamp-{"Datestamp":"2021-01-11"}
标签: javascript jquery json amazon-web-services aws-lambda