I've written two JavaScript functions to make PUT and GET calls to my API Gateway endpoint, but I'm having trouble with the PUT call. The GET function works correctly and returns the visitor count from my DynamoDB table. However, when I try to update the count using the PUT call, I receive an error message saying "Access-Control-Allow-Origin Missing Header". I can successfully perform both GET and PUT operations when testing the endpoint with Postman or locally. Any ideas on how to resolve this error would be appreciated.
#[SOLVED] Error updating visitor count through API Gateway using Javascript fetch call
1 messages · Page 1 of 1 (latest)
Sorry forgot to include the functions. Here are the functions
function init(){
updateData()
fetchData()
}
function updateData(){
const apiURL = "url-here";
const requestOptions = {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
}
};
fetch(apiURL, requestOptions)
.then(response => {
if(response.ok) {
console.log("Visitor count updated successfully.");
} else {
// Request failed
console.log("Visitor count update failed.");
}
})
.catch(error => {
console.error("Error updating visitor count:", error);
});
}
function fetchData(){
fetch("url-here", )
.then((response) => response.json())
.then((data) =>
document.getElementById('visitorNumber').innerHTML = data
);
}
I think it is CORS Issue.
This answer from other discord channel that explain the issue
"CORS is built into browsers for security purposes, however, if you're not using a browser then it bypasses CORS"
The solution is simple, return these headers alongside the value of visitors count.
# lambda_function.py
# Return the JSON response
return {
"body": json_count_dict,
"headers": {
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET",
"Content-Type": "application/json"
},
"statusCode": 200
}
Okay, so I have two Lambda functions: "put" and "get". Both of these functions return values, but neither of them includes the "Access-Control-Allow-Methods" header. I will add that in
you can reduce them to one function if you want.
The same function that updated the value using dynamodb.update_item will return the new value.
This is from performance perspective. (optional)
OK, so I've changed it to one function but I'm still getting the cors error
can post your github here, to debug the code.
or post the complete lambda functions(s) with the latest update. and the latest error you have.
to be able to help you better
ok here's the latest update to my Lambda function https://github.com/xxx/xxx/blob/main/xxx/serverless-resume-website/serverless_web
To test locally, I run sam local start-api. Then use Postman to send a put request. I am able to see the counter value
However, when attempting to do the same thing using the Js Fetch API, I encounter a CORS error.
ResumeAPI:
Type: Api
Properties:
Path: /counter
Method: put
no, i did not. How come I am able to send the request using postman
That solved CORS issue for me, didn't know much details, but i know that a preflight request will hit the api, if it didn't find that route it will fail, so you need to add that route and then also add if statement to check weather the request is coming from options or put request in your lambda.
If the request is options return 200
If it's the put request -which will come after the success of the options one- then do you dynamodb stuff
My advice to you is: just put this API route first, and integrate it with your lambda,
then head to cloudwatch logs to see what is going on when you hit your api.
That will boost your debugging skill, also don't hesitate to post any questions here.
It works now! In my template.yaml, I changed the API method from a PUT call to a GET call. I don't know why it wasn't working with a PUT call, but I will investigate this with CloudWatch.
Thank you so much for taking the time🙏
[SOLVED] Error updating visitor count through API Gateway using Javascript fetch call
yeah no problem.
just one question, did it work through fetch request through your website, or you just typed the api url and it shows the number?
because if you only typed the url in the browser, it will work because you specify that it will work on GET request which is what happen when you type your API in the browser. and it won't work when you were having it as PUT.
So just confirm with me if it worked through the fetch through the website or just by typing the API.
Sorry, I didn't see this earlier. I retrieved the data through the website. One of the issues I encountered earlier was that I was unable to make a PUT request using the JS fetch API, even though I was able to do so using Postman. I am trying to recreate the same error so I can figure out the cause