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

4

13

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.

Elsey answered 13/5, 2021 at 13:30 Comment(5)
You shouldn't be sending a body with a GET request. While not strictly prohibited by the spec it is unconventional and some servers may reject it.Antione
what do you mean? i am not, at least im not aware of it.Elsey
My bad. Misread the screenshot. What are your request headers set to?Antione
i didnt set them, never did that with a get request. If you instead mean in the API gateway, i setted nothing but those enabled automatically by enabling CORS or putting Lambda integrationElsey
This did the trick for me: https://mcmap.net/q/774178/-react-component-has-been-blocked-by-cors-policy-no-39-access-control-allow-origin-39-header-is-present-on-the-requested-resource.Tonsorial
J
7

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.

Judicative answered 15/5, 2021 at 9:41 Comment(5)
Dont know, i cant still up/dowvote because of low reputation. Thanks for the reply, btw. I solved by putting a simple string in the enable cors headers, so i dont think this was the solution to my problem - but thanks anyway. If i can do something for the downvote let me know.Elsey
No worries, if it is solved then good. :DJudicative
Don't be sorry, no worries, coding should be fun and I think some people really hate CORS XDJudicative
@Judicative Your solution solved my issue. You are a rockstar! Thank you so much!Muskmelon
@DmitriSanzharov Glad to help you.Judicative
A
4

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.

Avner answered 23/9, 2021 at 2:8 Comment(1)
I'm (i was) using Node.js as the runtime language for the lambda function, i solved the problem just by adding 'Origin' into the allow Control Allow Headers field of enable cors, so i dont think this was really the response to this problem, at least for me. Thanks anyway!Elsey
M
1

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

Muskmelon answered 5/6, 2021 at 19:22 Comment(2)
thanks for the reply! i solved the problem just by adding 'Origin' into the allow Control Allow Headers field of enable cors, so i dont think this is really the response to this problem, or maybe this also works? Also thanks forthe references, its always good to have something more to try :)Elsey
Yeah, I tried that originally to, but didn't work for me, for some reason. But the Headers into lambda worked. Anyway, we are unstoppable now. Next challenge here we come! Boom! =)Muskmelon
S
1

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.

Silage answered 12/3 at 23:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.