Search code examples
aws-lambdacorsaws-api-gateway

Access to fetch at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource


I have this api (method get) that is connected to a lambda function that does a simple select from a database, if i test the endpoint with postman with a null body it does work (if i understood, postman is not under the same CORS policy), as well as typing the endpoint on the browser. postman

browser

But when i try to do a fetch from a simple js, i get the error : Access to fetch at '...' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

enter image description here

I enabled CORS in API Gateway, both with the Enable CORS option enter image description here and with the Enable API Gateway CORS when creating a new resource enter image description here

If i test my endpoint with gateway, i also get that Allow-content-allow-origin : * is in my response header : enter image description here

What should i do to fix this problem?

here is the JS fetch :

    console.log("pre fetch");

Show();
console.log("post fetch");
function Show(){
fetch("...").then(onResponse);//.then(onJson);
}
function onResponse(response){
    console.log(response);
    return response.json();
}

I removed the onJson to avoid confusion, but even with that in its the same problem.


Solution

  • Try to include that in your function too, like this, I hope this would work:

    const headers = {'Content-Type':'application/json',
                        'Access-Control-Allow-Origin':'*',
                        'Access-Control-Allow-Methods':'POST,PATCH,OPTIONS'}
    const response = {
        statusCode: 200,
        headers:headers,
        body: JSON.stringify(X),
    };
    return response;
    

    Here X is the response that you want to return.