简体   繁体   中英

Enabling CORS to access AWS API Gateway?

I'm trying to access an AWS API Gateway with jQuery like:

$.ajax({
    method: 'GET',
    url: _config.api.invokeUrl + '/mymodel/' + id + '/attr',
    headers: {
        Authorization: authToken
    },
    data: {},
    contentType: 'application/json',
    success: function(result){
        console.log('success:'+result);
    },
    error: function ajaxError(jqXHR, textStatus, errorThrown) {
        console.error('Error: ', textStatus, ', Details: ', errorThrown);
        console.error('Response: ', jqXHR.responseText);
    }
});

However, jQuery/browser reports the CORS error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://sd98fsf98.execute-api.us-east-1.amazonaws.com/test/mymodel/123/attr. (Reason: CORS request did not succeed).

Clearly, I can't fix it by hosting my code from sd98fsf98.execute-api.us-east-1.amazonaws.com . I can't find any option in the Gateway API settings to disable this check. How do I bypass the CORS restriction?

You need to enable CORS in your API gateway. This sets us an options method which adds the required headers for cross-origin access.

In your API Gateway console: Actions -> Enable Cors[Select '*' for everyone] -> Deploy API CORS

After deploying the API, the requests will first get the headers from the options method and then redirect to the GET method and will succeed.

部署

Please find more information on enabling CORS in the AWS DOCS: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html

Hope this helps!

In addition to Ashwani Jha answer and peeebeee comment see this article: https://enable-cors.org/server_awsapigateway.html

Amazon API Gateway adds support for CORS enabling through a simple button in the API Gateway console. Unfortunately that button has a partial behavior, thus setting CORS correctly only for 200 answer (so not other HTTP status codes) and ignoring JQuery header support. The best solution considered so far is about avoiding to use the CORS button and set configurations manually. This can be achieved in a couple of steps:

  1. Log into API Gateway console
  2. Create all the REST resources that needs to be exposed with their methods before setting up CORS (if new resources/methods are created after enabling CORS, these steps must be repeated)
  3. Select a resource
  4. Add OPTIONS method, choose as integration type "mock"
  5. For each Method of a resource
  6. Go to Response Method
  7. Add all the response method that should be supported (ie 200, 500, etc.)
  8. For each response code set Response Headers to

    • X-Requested-With
    • Access-Control-Allow-Headers
    • Access-Control-Allow-Origin
    • Access-Control-Allow-Methods
  9. Go to Integration Response, select one of the created response codes, then Header Mappings

  10. Insert default values for headers example:
    • X-Requested-With: '*'
    • Access-Control-Allow-Headers: 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,x-requested-with'
    • Access-Control-Allow-Origin: '*'
    • Access-Control-Allow-Methods: 'POST,GET,OPTIONS'

This operation has to be repeated for each method, including the newly created OPTIONS

  1. Deploy the API to a stage
  2. Check using http://client.cors-api.appspot.com/client that CORS requests have been successfully enabled

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