ChatGPT解决这个技术问题 Extra ChatGPT

API Gateway CORS: no 'Access-Control-Allow-Origin' header

Although CORS has been set up through API Gateway and the Access-Control-Allow-Origin header is set, I still receive the following error when attempting to call the API from AJAX within Chrome:

XMLHttpRequest cannot load http://XXXXX.execute-api.us-west-2.amazonaws.com/beta/YYYYY. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403.

I attempted to GET the URL through Postman and it shows the above header is successfully passed:

https://i.stack.imgur.com/cowzz.png

And from the OPTIONS reponse:

https://i.stack.imgur.com/xRCeH.png

How can I call my API from the browser without reverting to JSON-P?

Do you have it set up on the S3? If so, could you put up the Bucket Policy? Make sure you have the method in your policy
API Gateway team here... If you use the 'Enable CORS' feature in the console, the configuration should be correct. My best guess would be that you aren't invoking the correct resource path in your API in the JavaScript that the browser is executing. If you attempt to make an API call to a non-existent method/resource/stage you'll receive a generic 403 with none of the CORS headers. I don't see how the browser could miss the Access-Control-Allow-Origin header if you're calling the right resource since the OPTIONS call in Postman clearly contains all the right CORS headers.
@RyanG-AWS the client is not signing the request because the API is authenticated by the resource it calls using a user-specific token, so the credentials are not a factor. I can call the API by visiting the URL directly in the browser and I get the appropriate response.
@makinbacon: Did you find a solution for this? I'm going through the same issue here.
My methods and stage were generated automatically by Lambda. I enabled CORS after the fact. Same errors as OP. I blew away the auto generated stuff, created a new API and methods, deployed to a new stage, and it worked fine.

r
riseres

I get the same problem. I have used 10hrs to findout.

https://serverless.com/framework/docs/providers/aws/events/apigateway/

// handler.js

'use strict';

module.exports.hello = function(event, context, callback) {

const response = {
  statusCode: 200,
  headers: {
    "Access-Control-Allow-Origin" : "*", // Required for CORS support to work
    "Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS 
  },
  body: JSON.stringify({ "message": "Hello World!" })
};

callback(null, response);
};

Fixed the problem I was having as well. Thank you for your answer!
FYI, there's an issue with the example presented here. If you have "Access-Control-Allow-Credentials": true, you can't have the wildcard * for Access-Control-Allow-Origin. This rule is enforced by the browser. See here and here
This is not working, Again shows same error Request header field access-control-allow-credentials is not allowed by Access-Control-Allow-Headers in preflight response.
For anyone curious, here is the official docs mentioning this: docs.aws.amazon.com/apigateway/latest/developerguide/… > For Lambda or HTTP proxy integrations, you can still set up the required > OPTIONS response headers in API Gateway. However, you must rely on the > back end to return the Access-Control-Allow-Origin headers because the > integration response is disabled for the proxy integration.
setting only "Access-Control-Allow-Origin" : "*" from lambda solved the issue
A
Alex R

If anyone else is running into this still - I was able to track down the root cause in my application.

If you are running API-Gateway with custom Authorizers - API-Gateway will send a 401 or 403 back before it actually hits your server. By default - API-Gateway is NOT configured for CORS when returning 4xx from a custom authorizer.

Also - if you happen to be getting a status code of 0 or 1 from a request running through API Gateway, this is probably your issue.

To fix - in the API Gateway configuration - go to "Gateway Responses", expand "Default 4XX" and add a CORS configuration header there. i.e.

Access-Control-Allow-Origin: '*'

Make sure to re-deploy your gateway - and voila!


For those wanting to do this with the AWS CLI, use: aws apigateway update-gateway-response --rest-api-id "XXXXXXXXX" --response-type "DEFAULT_4XX" --patch-operations op="add",path="/responseParameters/gatewayresponse.header.Access-Control-Allow-Origin",value='"'"'*'"'"'
note to myself - don't forget to deploy the API afterwards :)
Strange, this worked for me, but I didn't have to redeploy. I did try redeploying earlier. Not sure why it worked for me.
Adding the CORS header to 4XX allows you to see the actual error message instead of the CORS error.
Just FYI, the way to do this from the AWS console is to click on the method (i.e. "POST" then "enable CORS" then check off the 4XX options, then deploy.
l
lase

If you have tried everything regarding this issue to no avail, you'll end up where I did. It turns out, Amazon's existing CORS setup directions work just fine... just make sure you remember to redeploy! The CORS editing wizard, even with all its nice little green checkmarks, does not make live updates to your API. Perhaps obvious, but it stumped me for half a day.

https://i.stack.imgur.com/pQnoi.png


This was it. Literally working on this for two days. Not sure the logic in not at least prompting for a redeploy after you edit the gateway.
@ChrisChristensen glad you got it figured out - there's always something so relieving yet incredibly defeating about problems like this
This is the answer that is valid in 2020. Thanks
RE-DEPLOY RE-DPLOY RE-DEPLOY
I can't find this menu anywhere. I suspect many of these solutions are for REST api, not HTTP api.
C
Carlos Alberto Schneider

1) I needed to do the same as @riseres and some other changes.This are my response headers:

headers: {
            'Access-Control-Allow-Origin' : '*',
            'Access-Control-Allow-Headers':'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token',
            'Access-Control-Allow-Credentials' : true,
            'Content-Type': 'application/json'
        }

2) And

According to this documentation:

http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html

When you use proxy for lambda functions on API Gateway config, the post or get methods have no added headers, only the options does. You must do it manually in the response(server or lambda response).

3) And

Beside that, I needed to disable the 'API Key Required' option in my API gateway post method.


Yep, I think the subtle thing a lot of us miss initially is that once you configure your API Gateway integration for the Lambda function with "Use Lambda Proxy Integration", then you must do as you and others are stating and ensure the headers are added programmatically in your lambda's response. The auto-gen stuff that is created by "Enabling CORS" on an API Gateway and it creating an OPTIONS responder is great but doesn't get you all the way there if you set "Use Lambda Proxy integration" in the Integration Request within API Gateway.
This worked for me...after reading the manual properly : Important When applying the above instructions to the ANY method in a proxy integration, any applicable CORS headers will not be set. Instead, your backend must return the applicable CORS headers, such as Access-Control-Allow-Origin. docs.aws.amazon.com/apigateway/latest/developerguide/…
I suffered this issue in 2022 and spent hours trying to fix / troubleshoot - MAKE SURE YOU USE SINGLE QUOTES!
M
MannyC

Got my sample working: I just inserted 'Access-Control-Allow-Origin': '*', inside headers:{} in the generated nodejs Lambda function. I made no changes to the Lambda-generated API layer.

Here's my NodeJS:

'use strict';
const doc = require('dynamodb-doc');
const dynamo = new doc.DynamoDB();
exports.handler = ( event, context, callback ) => {
    const done = ( err, res ) => callback( null, {
        statusCode: err ? '400' : '200',
        body: err ? err.message : JSON.stringify(res),
        headers:{ 'Access-Control-Allow-Origin' : '*' },
    });
    switch( event.httpMethod ) {
        ...
    }
};

Here's my AJAX call

$.ajax({
    url: 'https://x.execute-api.x-x-x.amazonaws.com/prod/fnXx?TableName=x',
    type: 'GET',
    beforeSend: function(){ $( '#loader' ).show();},
    success: function( res ) { alert( JSON.stringify(res) ); },
    error:function(e){ alert('Lambda returned error\n\n' + e.responseText); },
    complete:function(){ $('#loader').hide(); }
});

I've found a lot of Amazon's documentation to be out-of-date, even with the "../latest/.." path fragment. After scrapping everthing about a week ago, the CORS button suddenly stated working properly. The API created the "ANY" method automatically and the CORS button created the "OPTIONS" method automatically - I added nothing to the API. The "GET" above works and I've since added an ajax "POST" which also works without me touching the API.
I spent almost two hours trying to figure out how to get Access-Control-Allow-Origin added to the method response using the AWS console, but this was also the only thing that worked for me.
V
Vishal Shetty

I just added headers to my lambda function response and it worked like a charm

exports.handler = async (event) => {
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hey it works'),
        headers:{ 'Access-Control-Allow-Origin' : '*' }
    };
    return response;
};

d
dz902

For Googlers:

Here is why:

Simple request, or, GET/POST with no cookies do not trigger preflight

When you configure CORS for a path, API Gateway will only create an OPTIONS method for that path, then send Allow-Origin headers using mock responses when user calls OPTIONS, but GET / POST will not get Allow-Origin automatically

If you try to send simple requests with CORS mode on, you will get an error because that response has no Allow-Origin header

You may adhere to best practice, simple requests are not meant to send response to user, send authentication/cookie along with your requests to make it "not simple" and preflight will trigger

Still, you will have to send CORS headers by yourself for the request following OPTIONS

To sum it up:

Only harmless OPTIONS will be generated by API Gateway automatically

OPTIONS are only used by browser as a precautious measure to check possibility of CORS on a path

Whether CORS is accepted depend on the actual method e.g. GET / POST

You have to manually send appropriate headers in your response


j
jizhihaoSAMA

For me, the answer that FINALLY WORKED, was the comment from James Shapiro from Alex R's answer (second most upvoted). I got into this API Gateway problem in the first place, by trying to get a static webpage hosted in S3 to use lambda to process the contact-us page and send an email. Simply checking [ ] Default 4XX fixed the error message.

https://i.stack.imgur.com/vYLwA.png


Where do you find this menu? I don't see it anywhere.
@NickH take a look at the picture from Ravi Ram. Under "Actions", there should be an item called "Enable CORS" and when you select that, the menu will show up.
R
Ravi Ram

I found a simple solution within

API Gateway > Select your API endpoint > Select the method (in my case it was the POST)

Now there is a dropdown ACTIONS > Enable CORS .. select it.

Now select the dropdown ACTIONS again > Deploy API (re-deploy it)

https://i.stack.imgur.com/JVAKq.png

It worked !


Why is this answer down-voted but there are other similar answers below?
For AWS based API gateway invoking, this solution works
A
Ankit Kumar Rajpoot

After Change your Function or Code Follow these two steps.

First Enable CORS Then Deploy API every time.


Thank you for that. Didn't notice the "Enable CORS" in the resource. Made me lose my mind.
This comment saved my day! I didn't know I had to "Deploy API" every time I changed the "Enable CORS"
R
RodP

I got mine working after I realised that the lambda authoriser was failing and for some unknown reason that was being translated into a CORS error. A simple fix to my authoriser (and some authoriser tests that I should have added in the first place) and it worked. For me the API Gateway action 'Enable CORS' was required. This added all the headers and other settings I needed in my API.


and re-deploy! :)
C
CDixon

For me, as I was using pretty standard React fetch calls, this could have been fixed using some of the AWS Console and Lambda fixes above, but my Lambda returned the right headers (I was also using Proxy mode) and I needed to package my application up into a SAM Template, so I could not spend my time clicking around the console.

I noticed that all of the CORS stuff worked fine UNTIL I put Cognito Auth onto my application. I just basically went very slow doing a SAM package / SAM deploy with more and more configurations until it broke and it broke as soon as I added Auth to my API Gateway. I spent a whole day clicking around wonderful discussions like this one, looking for an easy fix, but then ended up having to actually read about what CORS was doing. I'll save you the reading and give you another easy fix (at least for me).

Here is an example of an API Gateway template that finally worked (YAML):

Resources:
  MySearchApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: 'Dev'
      Cors:
        AllowMethods: "'OPTIONS, GET'"
        AllowHeaders: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
        AllowOrigin: "'*'"
      Auth:
        DefaultAuthorizer: MyCognitoSearchAuth
        Authorizers:
          MyCognitoSearchAuth:
            UserPoolArn: "<my hardcoded user pool ARN>"
            AuthType: "COGNITO_USER_POOLS"
        AddDefaultAuthorizerToCorsPreflight: False

Note the AddDefaultAuthorizerToCorsPreflight at the bottom. This defaults to True if you DON'T have it in your template, as as far as I can tell from my reading. And, when True, it sort of blocks the normal OPTIONS behavior to announce what the Resource supports in terms of Allowed Origins. Once I explicitly added it and set it to False, all of my issues were resolved.

The implication is that if you are having this issue and want to diagnose it more completely, you should visit your Resources in API Gateway and check to see if your OPTIONS method contains some form of Authentication. Your GET or POST needs Auth, but if your OPTIONS has Auth enabled on it, then you might find yourself in this situation. If you are clicking around the AWS console, then try removing from OPTIONS, re-deploy, then test. If you are using SAM CLI, then try my fix above.


A
Alexander

Deploying the code after enabling CORS for both POST and OPTIONS worked for me.


Thanks for your contribution however can you explain why it did workin for you? I invite you to read this guide to improve your answer : "How I write a good answer" here: stackoverflow.com/help/how-to-answer
1
10110

Make sure you're calling the right path.

Hitting a non-existing path, may cause CORS related errors, for whatever reason. Probably due to the fact that the 404 doesn't include CORS headers in its response.

Thanks to @jackko's comment on the initial question. This was my problem. Sounds silly but can happen to anyone.


Just after seeing this comment, I checked my URL. AHH! and it was indeed an issue with my URL. There was an additional '/' param added due to which I was getting CORS error. This comment literally saved me! Thanks a ton for pointing this out!!
Made this mistake second time. It was very frustrating.
J
James L.

I am running aws-serverless-express, and in my case needed to edit simple-proxy-api.yaml.

Before CORS was configured to https://example.com, I just swapped in my site's name and redeployed via npm run setup, and it updated my existing lambda/stack.

#...
/:
#...
method.response.header.Access-Control-Allow-Origin: "'https://example.com'"
#...
/{proxy+}:
method.response.header.Access-Control-Allow-Origin: "'https://example.com'"
#...

C
CamHart

In my case, since I was using AWS_IAM as the Authorization method for API Gateway, I needed to grant my IAM role permissions to hit the endpoint.


Man am I glad I left this comment. This keeps happening to me :D.
I love finding my own solution to a future reoccurring issue.
v
vijayraj34

In my case I enabled all the methods and gateway responses. Then it worked like a charm. Don't forget to deploy.

https://i.stack.imgur.com/a4FNU.png


I've faced this error too. It's important to enable logging at your lambda level (if you're using a proxy [API gateway -> lambda] for example) as well as at api gateway to understand where the issue is happening. In my case, I did not have 4xx or 5xx enabled for CORS and i had to check lambda cloudwatch logs to understand where the error was happening.
M
Manifest Man

For Python, as @riseres mentioned, after importing json, etc...

// lambda handler

def hello(event, context, callback):
response = {
  statusCode: 200,
  headers: {
    "Access-Control-Allow-Origin" : "*", # Required for CORS support, to work, also you should instead specify the proper origin if credentials are mandatory
    "Access-Control-Allow-Credentials" : True # Required for cookies, authorization headers with HTTPS 
  },
  body: json.dumps({ "message": "Hello World!" })
}

callback(null, response);
}

M
Michael Seibt

Another root cause of this problem might be a difference between HTTP/1.1 and HTTP/2.

Symptom: Some users, not all of them, reported to get a CORS error when using our Software.

Problem: The Access-Control-Allow-Origin header was missing sometimes.

Context: We had a Lambda in place, dedicated to handling OPTIONS request and replying with the corresponding CORS headers, such as Access-Control-Allow-Origin matching a whitelisted Origin.

Solution: The API Gateway seems to transform all headers to lower-case for HTTP/2 calls, but maintains capitalization for HTTP/1.1. This caused the access to event.headers.origin to fail.

Check if you're having this issue too:

Assuming your API is located at https://api.example.com, and your front-end is at https://www.example.com. Using CURL, make a request using HTTP/2:

curl -v -X OPTIONS -H 'Origin: https://www.example.com' https://api.example.com

The response output should include the header:

< Access-Control-Allow-Origin: https://www.example.com

Repeat the same step using HTTP/1.1 (or with a lowercase Origin header):

curl -v -X OPTIONS --http1.1 -H 'Origin: https://www.example.com' https://api.example.com

If the Access-Control-Allow-Origin header is missing, you might want to check case sensitivity when reading the Origin header.


N
Nigel Atkinson

In addition to others comments, something to look out for is the status returned from your underlying integration and if the Access-Control-Allow-Origin header is returned for that status.

Doing the 'Enable CORS' thing only sets up 200 status. If you have others on the endpoint, e.g 4xx and 5xx, you need to add the header yourself.


t
thenewpotato

For those using Cognito authorizers in API Gateway, there's actually no need to set custom Gateway Responses. The API Gateway blocks pre-flight because they're "unauthorized" by default AWS logic.

Fortunately, there's a built-in parameter to fix this. Simply add AddDefaultAuthorizerToCorsPreflight: False to your API Authorizer and API Gateway will disable authentication for pre-flight requests. Here's the documentation, and an example setup:

MyApi:
Type: AWS::Serverless::Api
Properties:
  StageName: Prod
  Cors: 
    AllowHeaders: "'*'"
    AllowMethods: "'*'"
    AllowOrigin: "'*'"
  Auth:
    DefaultAuthorizer: MyCognitoAuthorizer
    AddDefaultAuthorizerToCorsPreflight: False
    Authorizers:
      MyCognitoAuthorizer:
        UserPoolArn: !GetAtt MyCognitoUserPool.Arn

E
Ericson Willians

For future sufferers:

This cursed problem haunted me once again and this time it was because I was sending a custom header:

let headers = {
  'Content-Type': 'application/json',
  'Is-Web': true,
  Authorization: `Bearer ${accessToken}`,
};

This "Is-Web" custom header made API Gateway block my requests and masked it as a CORS error. If you're sending one, just remove it and test it. Almost lost a whole day of work because of this.


E
Ericson Willians

In my case, I was simply writing the fetch request URL wrong. On serverless.yml, you set cors to true:

register-downloadable-client:
    handler: fetch-downloadable-client-data/register.register
    events:
      - http:
          path: register-downloadable-client
          method: post
          integration: lambda
          cors: true
          stage: ${self:custom.stage}

and then on the lambda handler you send the headers, but if you make the fetch request wrong on the frontend, you're not going to get that header on the response and you're going to get this error. So, double check your request URL on the front.


D
Draken

In Python you can do it as in the code below:

{ "statusCode" : 200,
'headers': 
    {'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': "*"
     },
"body": json.dumps(
    {
    "temperature" : tempArray,
    "time": timeArray
    })
 }