使用AWS re:Post即您表示您同意 AWS re:Post 使用条款

API Gateway CORS issue using JS Fetch

0

I've seen this question asked a few times, but, there doesn't seem to be clear response.

I've got an API Gateway attached to a Lambda function, a get call to the API should return a value, in this case either 0 or 1.

In postman this works fine, but, when I try it in my deployed code (which is JS) the fetch call fails:

Access to fetch at '[APIGATEWAYURL]' from origin 'http://localhost:8080' 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. (this also fails with a version in my s3 bucket.)

This answer: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors-console.html shows an option to enable CORS, but I don't see that on my console...

已提问 9 个月前1001 查看次数
1 回答
2
已接受的回答

Your Lambda function needs to return the right headers in the response, for example:

const responseHeaders = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*',
};
const body = { 'userId': 13232 };
return {
  statusCode: 200,
  headers: responseHeaders,
  body: JSON.stringify(results),
};

You shouldn't have to configure CORS after you add those headers. But if you want to configure CORS on API Gateway then navigate to API Gateway in the console and click to open the API Gateway instance you want to change. Under details for that API Gateway open the side menu and make sure you are under resources, then you can enable CORS for a specific resource such as "/users". If you add methods then you'll need to add another header for Access-Control-Allow-Methods such as 'Access-Control-Allow-Methods': 'GET'.

AWS
已回答 9 个月前
profile picture
专家
已审核 7 个月前
profile picture
专家
已审核 9 个月前
profile picture
专家
已审核 9 个月前
  • Amazing - thank you.

  • Furthermore, it worked on Postman and not in the fetch call because Postman is a developer tool. It doesn't enforce CORS by default, so your request is treated as "SAME ORIGIN". Your browser is also a developer tool so if you test your API directly in the browser, it will work just fine BUT the scripts like js are treated differently by the browser and the requests made by a script are enforced with "CROSS ORIGIN" and hence it pops a CORS error.

您未登录。 登录 发布回答。

一个好的回答可以清楚地解答问题和提供建设性反馈,并能促进提问者的职业发展。

回答问题的准则