redbite
redbite

Reputation: 261

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.

Upvotes: 13

Views: 119672

Answers (4)

For Lambda function URL:

In the AWS console, go to Lambda -> Functions -> (select the function) -> Configuration -> Function URL -> Edit.

Check Configure cross-origin resource sharing (CORS) and enter * for Allow origin, Allow headers, and Allow methods

Save.

Upvotes: 1

fruitloaf
fruitloaf

Reputation: 2892

I made a video on how to fix this.

You need to go into the Lambda function and add special code:

original (does NOT work):

exports.handler = async (event) => {
    // TODO implement
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

new one, that works:

exports.handler = async (event) => {
    // TODO implement
    const response = {
        statusCode: 200,
                headers: {
            "Access-Control-Allow-Headers" : "Content-Type",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "OPTIONS,POST,GET"
        },
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

You can find this solution in here: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html

Only you need to replace the:

  "Access-Control-Allow-Origin": "https://www.example.com",

with

            "Access-Control-Allow-Origin": "*",

Special thanks to user, KnowledgeGainer

ALSO, you need to enable CORS on Gateway API side, just follow instruction from here: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors-console.html

Upvotes: 1

JACKSON MUIRU
JACKSON MUIRU

Reputation: 101

If you are using Node.js you needs to install cors. npm install cors. After installing cors, include it in the page where you are using fetch function as shown below; const cors = require('cors'); app.use(cors()); and the error will be solved.

Upvotes: 4

KnowledgeGainer
KnowledgeGainer

Reputation: 1097

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.

Upvotes: 7

Related Questions