简体   繁体   中英

Request fails in browser, but returns 200 in fiddler with correct results, blocked by CORS policy

I am trying to set up an AWS lambda function, however when I call the endpoint, I am getting this error message back in the console.

Access to fetch at 'https://* .execute-api.eu-west-1.amazonaws.com/default/ ' from origin 'http://localhost:3000' 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.

I have set the CORS policy on the AWS Gateway

在此处输入图像描述

Here is my request code... I am just trying to print out the body of the response for testing purposes.

const response = await fetch(
  'https://**********.execute-api.eu-west-1.amazonaws.com/default/**************',
  {
    method: 'POST',
    body: "{'test': 'test'}",
    headers: {
      'X-Api-Key': '*****************************',
    },
  }
);
const text: any = await response.text();
console.log(text);

Weirdly when I look in fiddler, it is sending the OPTIONS and also returning a correct response, which is currently just printing out the different headers passed to the function.

在此处输入图像描述

If you've lambda proxy integration enabled you'll have to add headers from lambda.

From AWS documentation CORS section

For a Lambda proxy integration or HTTP proxy integration, you can still set up the required OPTIONS response headers in API Gateway. However, your backend is responsible for returning the Access-Control-Allow-Origin and Access-Control-Allow-Headers headers, because a proxy integration doesn't return an integration response.

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

you can read more here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM