I’m trying to POST an item in VS Code to my DynamoDB table via axios. I’m able to POST an item successfully via Postman, however when I try to POST an item with axios I get a 404 response error (below).
I’m wondering if I’m missing something when trying to POST an item via axios (below).
axios({
'method': 'post',
'url': 'https://na9blqj5y5.execute-api.us-east-1.amazonaws.com/test',
'Content-Type': 'application/json',
'data': {
'body': eraseThis,
}
})
.then((response) => {
return console.log('axiosResp', response);
})
.catch((err) => console.error('axios', err))
One thought that I had is that I should be importing the AWS SDK and invoke my lambda function with my credentials from that (below)? Any help would be greatly appreciated!
This is a successful POST request in Postman.
Now I'm getting a CORS error I had a few weeks ago (even after enabling CORS on the API resource in the API Gateway interface).
Below is the updated code using the aws-sdk
Your examples are hard to follow because they don't match.
So right off I'm wondering if you just have different code deployed to different stages? Assuming you've ruled that out though and that's not the case I think what you mean to say is that your axios call made via browser fails whereas postman works.
That's actually expected behavior because postman isn't a browser and bypasses the CORS restrictions that browsers implement. There are plenty of existing questions here that explain that so I'm not going into that further.
I believe the fix for this is to update your lambda handler (the actual lambda proxy that returns a response) to always return a Access-Control-Allow-Origin header as documented by AWS here. To allow all origins you can use a wildcard *. ex:
headers: {
"Access-Control-Allow-Headers" : "Content-Type",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "OPTIONS,POST,GET"
}
Make sure you understand the implications of using *, which is a discussion for a different post.
Not sure what I did, but the call to dynamodb randomly started working. I think I had a syntax error, or something..