I made todo application, i could process GET,POST method in lambda function but i got error when invoke delete method.Here i want to delete data in dynamo db by making delete query from axios through lambda function
This is axios delete function,it send {"data": {"id":this.id}}
to 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()
},
I have lambda api for delete
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 above with
{
"body": "{\"data\":{\"id\":\"1633613467228\"}}"
}
and i got statusCode 200 and no error and i check that the data is deleted in dynamo db
i have a DELETE method API that is related to the lambda function above, and i test delete method api above by giving query {item} => id=1633613467228 , this is the id i want to delete
but it gave me result
{
"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
and i test with postman
https://94sc9th9bi.execute-api.ap-northeast-1.amazonaws.com/prod/item?id=1633613467228
i got error, it seem that the query ?id=1633613467228 is not work
i also test the application , i got CORRS/network error in console although i already set access control orign to *
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
so my questions are:
1.why delete method in api above result in internal server error and how can i test the method. i also got confused of the different between test in api gateway and test in lambda function. Is my test data wrong format?
- in axios i have
"data": {"id":this.id}})
, isKey:{id: body.data.id}
right way to get the data send by axios in aws lambda function?
this is the eror from amazon cloudwatch. it seems 'data' is null.
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)"
]
}
i test lambda function with body and got 200
test lambda with body
i test api gateway by add query for delete it gave internal server error
enter image description here
i tried to make request by using axios here, i want to delete task which name is 'aa' with id = 1633601975370
delete task name="aa"
as you can see, body with id is sent, but there is error when axios request delete api
error i got in console
error in console
amaxon cloudwatch log error
enter image description here
CodePudding user response:
I got a CORS error the in console even though I've already set
Access-Control-Allow-Origin
to*
The question is:
Are you trying to enable CORS for a Lambda proxy integration or a Lambda non-proxy integration?
Enabling CORS will differ based on the integration type.
First, refer to the Enable CORS on a resource using the API Gateway console section of the Amazon API Gateway developer guide as it includes images etc.
Follow the guide for proxy & non-proxy.
If it is a non-proxy integration, you're done.
If it's a proxy integration (which I don't think it is), your request will still fail - a DELETE
request is classed as a complex request by the CORS specification.
This means that if you are making a call to this endpoint using a web app, you may have allowed all origins but you haven't specified which HTTP methods to allow (which the web app will request for in the form of a preflight
request before the DELETE
request).
So you'll need to also set the Access-Control-Allow-Methods
header to *
to allow HTTP DELETE
in the response returned by your Lambda:
const response = {
body: JSON.stringify(dynamoDBResponse),
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "*",
"Access-Control-Allow-Credentials": true
}
};