简体   繁体   中英

XMLHttpRequest - AWS API Gateway No 'Access-Control-Allow-Origin' header is present on the requested resource

When I try to open a request via browser I get the following error:

XMLHttpRequest cannot load https://............us-east-1.amazonaws.com/v1/...../select . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost ' is therefore not allowed access. The response had HTTP status code 401.

I know that it can be a CORS error, but i'm not managing to solve the problem.

I'm using AWS API Gateway and I already enabled the CORS on the API, enabled the CORS on S3 and all the permissions are ok.

xmlHttp.open( "GET", "https://.......execute-api.us-east-1.amazonaws.com/v1/....../select", true);
xmlHttp.send();

I've checked the API GET method and OPTIONS method and all things works fine.

Additional information:

When I use the API without define the "Authorization" on the Method Request, everthing works fine, but when I put the authorizer I get the error above.

在此处输入图片说明

在此处输入图片说明

Another question:

Need I to allow CORS on the Lambda functions as well?

Thanks a lot for all help

The issue is a known bug with API Gateway. When you put authorization on the API, if the auth fails (access denied for example) the CORS headers are not applied to the response. If authorization succeeds the headers will be applied to the response.

We are hoping to fix this soon, but unfortunately I can't provide an ETA.

It's because you may be getting a cached result.

In API gateway > API > Authorizers try changing Result TTL in seconds to 0 from you custom authorizer which is by default 300 seconds.

In autogenerated policy, the policy is cached so when the second request arrives, it doesn't match with the cached policy and returns an error.

Cache is created with token, authorizer, environment, your API, and deployment

If you set TTL to 0 then it won't be caching and you can test you API

You need to redeploy your API to reflect this changes

This is one solution that I have tried and another one is changing custom generated policy and be more specific in resources. You can provide each specific API as an array of resources.

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