我做了todo应用程序,我可以在lambda函数中处理GET,POST方法,但在调用删除方法时出现错误。我想删除数据在发电机db通过删除查询通过lambda函数从axios
这是axios的delete函数,它将{"data": {"id":this.id}}
发送到lambda
axios.delete('https://94sc9th9bi.execute-api.ap-northeast-1.amazonaws.com/prod/item',
{ "data": {"id":this.id}}).then(
res => {
console.log(res.data.id)
}).catch(err => {console.log(err)})
this.getalltask()
},
我λapi删除
const AWS = require('aws-sdk')
const docClient = new AWS.DynamoDB.DocumentClient()
exports.handler = async (event) => {
console.log(event)
let body = JSON.parse(event.body);
const scanItemPayload = {
TableName: 'aws-training',
Key:{
id: body.data.id
}
}
console.log(body);
const dynamoDBResponse = await docClient.delete(scanItemPayload).promise()
console.log(dynamoDBResponse)
const response = {
body: JSON.stringify(dynamoDBResponse),
statusCode: 200,
headers: {
"Access-Control-Allow-Origin" : "*", // Required for CORS support to work
"Access-Control-Allow-Credentials" : true, // Required for cookies, authorization headers with HTTPS
},
};
return response;
};
i test lambda with
{
"body": "{"data":{"id":"1633613467228"}}"
}
,我得到statusCode 200,没有错误,我检查数据被删除在dynamo db
我有一个与上面的lambda函数相关的DELETE方法API,并且我通过给出查询{item} =>Id =1633613467228,这是我要删除的Id
但是它给了我结果
{
"message": "Internal server error"
}
with error log
Execution log for request f83e7e01-52ca-498d-b3e6-34d972510ad8
Fri Oct 08 15:50:00 UTC 2021 : Starting execution for request: f83e7e01-52ca-498d-b3e6-34d972510ad8
Fri Oct 08 15:50:00 UTC 2021 : HTTP Method: DELETE, Resource Path: /item
Fri Oct 08 15:50:00 UTC 2021 : Method request path: {}
Fri Oct 08 15:50:00 UTC 2021 : Method request query string: {id=1633613467228}
Fri Oct 08 15:50:00 UTC 2021 : Method request headers: {}
Fri Oct 08 15:50:00 UTC 2021 : Method request body before transformations:
Fri Oct 08 15:50:00 UTC 2021 : Endpoint request URI: https://lambda.ap-northeast-1.amazonaws.com/2015-03-31/functions/arn:aws:lambda:ap-northeast-1:184371581740:function:aws-training-20211006-p-delete/invocations
我测试邮差
https://94sc9th9bi.execute-api.ap-northeast-1.amazonaws.com/prod/item?id=1633613467228
我得到错误,似乎查询?id=1633613467228是不工作
我还测试了应用程序,我得到了控制台的CORRS/网络错误,尽管我已经将访问控制原点设置为*
Access to XMLHttpRequest at 'https://94sc9th9bi.execute-api.ap-northeast-1.amazonaws.com/prod/item?' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
index.vue?0f48:64 Error: Network Error
at createError (createError.js?2d83:16)
at XMLHttpRequest.handleError (xhr.js?b50d:117)
xhr.js?b50d:210 DELETE https://94sc9th9bi.execute-api.ap-northeast-1.amazonaws.com/prod/item? net::ERR_FAILED 502
我的问题是:
1。为什么删除方法api之上导致内部服务器错误,我怎么能测试方法。我也对API网关测试和lambda函数测试之间的区别感到困惑。我的测试数据格式是否错误?
- 在axios中我有
"data": {"id":this.id}})
,是Key:{id: body.data.id}
正确的方式来获得axios在aws lambda函数发送的数据?
这个错误来自amazon cloudwatch。看来'data'是空的。
START RequestId: 8197a2bb-b045-438b-8b37-4467687006e3 Version: $LATEST
2021-10-09T06:28:31.894Z 8197a2bb-b045-438b-8b37-4467687006e3 INFO { key: { id: '1633613467228' } }
2021-10-09T06:28:31.927Z 8197a2bb-b045-438b-8b37-4467687006e3 ERROR Invoke Error
{
"errorType": "SyntaxError",
"errorMessage": "Unexpected token u in JSON at position 0",
"stack": [
"SyntaxError: Unexpected token u in JSON at position 0",
" at JSON.parse (<anonymous>)",
" at Runtime.exports.handler (/var/task/index.js:12:21)",
" at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
]
}
END RequestId: 8197a2bb-b045-438b-8b37-4467687006e3
REPORT RequestId: 8197a2bb-b045-438b-8b37-4467687006e3 Duration: 56.29 ms Billed Duration: 57 ms Memory Size: 128 MB Max Memory Used: 72 MB Init Duration: 399.98 ms
START RequestId: ff096041-a1fb-4349-abbc-a5d422e034d6 Version: $LATEST
2021-10-09T06:29:04.648Z ff096041-a1fb-4349-abbc-a5d422e034d6 INFO {
resource: '/item',
path: '/item',
httpMethod: 'DELETE',
headers: null,
multiValueHeaders: null,
queryStringParameters: { id: '1633613467228' },
multiValueQueryStringParameters: { id: [ '1633613467228' ] },
pathParameters: null,
stageVariables: null,
requestContext: {
resourceId: '2gw7om',
resourcePath: '/item',
httpMethod: 'DELETE',
extendedRequestId: 'G7V7mFskNjMF-vg=',
requestTime: '09/Oct/2021:06:29:04 +0000',
path: '/item',
accountId: '184371581740',
protocol: 'HTTP/1.1',
stage: 'test-invoke-stage',
domainPrefix: 'testPrefix',
requestTimeEpoch: 1633760944483,
requestId: 'f7596258-871a-4b15-b62c-11d434e176b4',
identity: {
cognitoIdentityPoolId: null,
cognitoIdentityId: null,
apiKey: 'test-invoke-api-key',
principalOrgId: null,
cognitoAuthenticationType: null,
userArn: 'arn:aws:iam::184371581740:user/user07',
apiKeyId: 'test-invoke-api-key-id',
userAgent: 'aws-internal/3 aws-sdk-java/1.12.71 Linux/5.4.134-73.228.amzn2int.x86_64 OpenJDK_64-Bit_Server_VM/25.302-b08 java/1.8.0_302 vendor/Oracle_Corporation cfg/retry-mode/standard',
accountId: '184371581740',
caller: 'AIDASV3LHCMWIZKMZMLPE',
sourceIp: 'test-invoke-source-ip',
accessKey: 'ASIASV3LHCMWBJROEHQN',
cognitoAuthenticationProvider: null,
user: 'AIDASV3LHCMWIZKMZMLPE'
},
domainName: 'testPrefix.testDomainName',
apiId: '94sc9th9bi'
},
body: null,
isBase64Encoded: false
}
2021-10-09T06:29:04.667Z ff096041-a1fb-4349-abbc-a5d422e034d6 ERROR Invoke Error
{
"errorType": "TypeError",
"errorMessage": "Cannot read property 'data' of null",
"stack": [
"TypeError: Cannot read property 'data' of null",
" at Runtime.exports.handler (/var/task/index.js:16:19)",
" at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
]
}
END RequestId: ff096041-a1fb-4349-abbc-a5d422e034d6
REPORT RequestId: ff096041-a1fb-4349-abbc-a5d422e034d6 Duration: 180.66 ms Billed Duration: 181 ms Memory Size: 128 MB Max Memory Used: 73 MB
START RequestId: 1adde91a-ce53-4d2f-8fa8-d296352fc689 Version: $LATEST
2021-10-09T06:30:01.788Z 1adde91a-ce53-4d2f-8fa8-d296352fc689 INFO { key: { id: '1633613467228' } }
2021-10-09T06:30:01.807Z 1adde91a-ce53-4d2f-8fa8-d296352fc689 ERROR Invoke Error
{
"errorType": "SyntaxError",
"errorMessage": "Unexpected token u in JSON at position 0",
"stack": [
"SyntaxError: Unexpected token u in JSON at position 0",
" at JSON.parse (<anonymous>)",
" at Runtime.exports.handler (/var/task/index.js:12:21)",
" at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
]
}
截取axios查看数据
i test lambda function with body并得到200
test lambda with body
输入图片描述
输入图片描述
我试图在这里使用axios发出请求,我想删除id = 1633601975370的名称为'aa'的任务
删除任务名称="aa">
可以看到,body with id被发送,但是axios请求删除api时出现错误
error I got in console
error in console
amazon cloudwatch日志错误
输入图像描述
cloudwatch日志错误
尽管我已经将
Access-Control-Allow-Origin
设置为*
,但我在控制台得到了CORS错误
问题是:
您是否尝试为Lambda代理集成或Lambda非代理集成启用CORS ?
启用CORS将根据集成类型不同。
首先,参考Amazon API Gateway开发人员指南的使用API Gateway控制台部分在资源上启用CORS,因为它包含图像等。
遵循代理指南&非代理。
如果是非代理集成
如果是代理集成(我不认为是),你的请求仍然会失败-DELETE
请求被CORS规范归类为复杂请求。
这意味着如果你使用web应用程序对这个端点进行调用,你可能已经允许所有起源,但你没有指定允许哪些HTTP方法(web应用程序将在DELETE
请求之前以preflight
请求的形式请求)。
因此,您还需要将Access-Control-Allow-Methods
标头设置为*
,以便在Lambda返回的响应中允许HTTPDELETE
:
const response = {
body: JSON.stringify(dynamoDBResponse),
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "*",
"Access-Control-Allow-Credentials": true
}
};