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

26

177

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:

Passed headers

And from the OPTIONS reponse:

Response headers

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

Peroxide answered 4/2, 2016 at 0:51 Comment(24)
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 policyCominform
No @Cominform it is set up on another server for testing. I also have tried it while accessing the file locally from my PC and through other servers. Is there something I need to configure on the page hosting server to allow use of CORS? My understanding is that only the API server needs settings altered for CORS.Peroxide
So have you added a CORS policy to your API though? And what do you mean 'page hosting server'? Just a regular server or a static serverCominform
Yes, through the "Enable CORS" options in AWS API GatewayPeroxide
Gotcha, and did you include a policy with that?Cominform
This may or may not help but found this link: #10637111Cominform
Does the OPTIONS call succeed? Can you post the results of the OPTIONS call? This is the result you would see if the OPTIONS call fails due to auth or other errorsIngrained
I added the OPTIONS result to the questionPeroxide
So what exactly are you trying to do? GET data or find out what connection OPTIONS are available. Also if you are using CloudFront, sometimes it takes a while for them to deliver your files to the CDN. This only applies if you set up the CloudFront in the last hour or two.Cominform
Hey check this on out too. This guy is using AJAX too. #20035601Cominform
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.Amphiprostyle
@JackKohn I verified that the resource path is correct and was able to successfully access the method directly via the URL in Chrome. Also, the error explicitly mentions the lack of the 'Access-Control-Allow-Origin' header.Peroxide
Most times this misleading error message is due to the GET failing with a 404 or a 403 error. In those cases the CORS headers aren't returned by the service. Is the client signing the request with credentials and is the IAM policy for those credentials authorized to call that API/method? Can you confirm that the URL used by the client is correct?Ingrained
@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.Peroxide
@makinbacon: Did you find a solution for this? I'm going through the same issue here.Woodshed
@Woodshed I think I removed the API and re-added it, then enabled CORS and it worked for me. I am still not sure exactly what changed causing it to work.Peroxide
@makinbacon: Ah, I just tried that, and it works for some strange reasons. I have hundreds of resources and methods and it's going to be one hell of a task to recreate all of them. This can also be achieved by manually specifying the header in the Integration Response. Either way, it's a lot of work. Thanks for the help.Woodshed
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.Africah
just tried this, with no luck :(Pneumonectomy
See my answer here it could be related to API key issue, #34325509Aggregate
We need to see the headers in the response from the actual ajax request that is throwing said error. Postman results aren't really all that useful. The error states that said header doesn't exist, i'm more inclined to believe that it doesn't exist than an error is being thrown stating that something doesn't exist when it actually does.Cytoplasm
The response had HTTP status code 403 specifically hints that you're receiving an error response, and the error response likely does not have said cors header.Cytoplasm
My solution was delete API Gateway and Create a new one, enble cors. Thanks!!!Ketron
Deleting and recreating the resource did not help me. I have a resource with GET and OPTIONS and only the OPTIONS gets the headers even though in the CORS screen both methods are checked.Nazarius
M
183

I got into the same problem. I have spent 10hrs to find out the below solution.

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);
};
Mm answered 26/3, 2017 at 12:56 Comment(11)
Fixed the problem I was having as well. Thank you for your answer!Reedy
I don't use serverless, but this solved my problem. Guess you need to pass those headers out from the actual source.Newly
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 hereTemplar
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.Must
how can you do this with java RequestHandler<RequestClass, ResponseClass> class?Texture
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.Preece
setting only "Access-Control-Allow-Origin" : "*" from lambda solved the issueMephitic
@Mm if Access-Control-Allow-Credentials has to be domain specific as @Templar said, you should edit the answer to clarify that because a lot of people aren't going to read the comments to check thatAmitosis
When setting up the Lambda there is some information text: Cross-origin resource sharing (CORS) CORS is required to call your API from a webpage that isn’t hosted on the same domain. To enable CORS for a REST API, set the Access-Control-Allow-Origin header in the response object that you return from your function code.Anarchy
You saved me too, I also wasted a couple of hours on this.Concordance
I have hit this a few times and forgot to add that header to my Lambda response.Consignment
B
162

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!

Builder answered 19/2, 2018 at 6:46 Comment(10)
@efong5 glad it helped someone!Builder
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='"'"'*'"'"'Agora
I'm not using custom Authorizers and still needed this as my request had bad JSON in it - thank you!Chansoo
note to myself - don't forget to deploy the API afterwards :)Beasley
Strange, this worked for me, but I didn't have to redeploy. I did try redeploying earlier. Not sure why it worked for me.Traduce
Adding the CORS header to 4XX allows you to see the actual error message instead of the CORS error.Chyack
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.Maki
Just tried this but got this error in the browser: "Response to preflight request doesn't pass access control check: It does not have HTTP ok status." Any ideas? I know I can set the status code for all 4XX requests (say, to 200), but that doesn't sound like terribly good practiceStowell
if you wish to do it through cdk, then this is how you do it : docs.aws.amazon.com/cdk/api/v1/docs/…Earthly
And see this if you're brave enough to want to try set this up via Serverless: https://mcmap.net/q/144217/-aws-api-gateway-responses-via-serverless-framework/765294Agora
P
47

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.

enter image description here

Park answered 3/12, 2018 at 18:22 Comment(5)
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.Koby
@ChrisChristensen glad you got it figured out - there's always something so relieving yet incredibly defeating about problems like thisPark
This is the answer that is valid in 2020. ThanksCrankcase
RE-DEPLOY RE-DPLOY RE-DEPLOYMeemeece
I can't find this menu anywhere. I suspect many of these solutions are for REST api, not HTTP api.Rugger
B
28

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.

Brian answered 6/4, 2017 at 20:12 Comment(5)
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.Haynor
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/…Vulcanism
I suffered this issue in 2022 and spent hours trying to fix / troubleshoot - MAKE SURE YOU USE SINGLE QUOTES!Vowelize
This is the correct answer, I added these headers and it works fine! Thank you!Laski
'Access-Control-Allow-Credentials' can't be set to true if 'Access-Control-Allow-Origin' is set to *.Headword
P
14

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(); }
});
Pekan answered 17/4, 2017 at 10:24 Comment(2)
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.Pekan
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.Historiated
A
12

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
Adlay answered 28/11, 2019 at 4:27 Comment(0)
A
12

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.

enter image description here

Armilda answered 14/7, 2020 at 1:34 Comment(2)
Where do you find this menu? I don't see it anywhere.Endosmosis
@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.Armilda
A
11

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;
};
Ant answered 26/4, 2020 at 9:23 Comment(0)
T
8

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)

enter image description here

It worked !

Tol answered 7/6, 2019 at 18:53 Comment(0)
G
4

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.

Gynecoid answered 25/1, 2021 at 12:48 Comment(1)
AddDefaultAuthorizerToCorsPreflight: False is the key, indeed. Thanks !Gainsborough
Y
3

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.

Yetta answered 15/7, 2018 at 15:46 Comment(1)
and re-deploy! :)Stale
E
3

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

Encasement answered 13/1, 2020 at 12:19 Comment(1)
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-answerEngen
N
3

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

enter image description here

Nuncle answered 12/4, 2021 at 19:7 Comment(1)
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.Certain
A
2

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.

Analyzer answered 25/5, 2021 at 22:56 Comment(2)
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!!Molarity
Made this mistake second time. It was very frustrating.Shyamal
A
2

I have been having this issue for quite sometime. I endend up putting this to my python lambda function

 response ={
        'statusCode': statusCode,
        'headers':{
             'Access-Control-Allow-Headers': 'Content-Type',
             'Access-Control-Allow-Origin': '*',
             'Access-Control-Allow-Methods': 'OPTIONS,POST,GET'
                  },
                  'body':json.dumps(body)
              }
    return response 

I hope this helps someone out there

Anasarca answered 23/7, 2022 at 9:24 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Orangeman
A
1

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'"
#...
Agnomen answered 7/12, 2018 at 0:34 Comment(0)
E
1

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.

Exum answered 21/4, 2019 at 9:31 Comment(2)
Man am I glad I left this comment. This keeps happening to me :D.Exum
I love finding my own solution to a future reoccurring issue.Preside
V
1

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.

Vivid answered 17/5, 2019 at 9:59 Comment(0)
S
1

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
Stowell answered 14/7, 2021 at 16:16 Comment(0)
S
1

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);
}
Severini answered 2/9, 2021 at 1:56 Comment(0)
C
0

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.

Cheongsam answered 30/10, 2019 at 2:25 Comment(0)
P
0

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.

Phosphoresce answered 16/12, 2021 at 16:41 Comment(1)
Got the same issue for me. I don't have any other headers other than Authorization. I added it as follows. Allow CORS > ( scroll down ) > Additional Settings > Access-Control-Expose-Headers this worked ✅. But Kindly someone add if this if fine.Milter
A
0

Make sure that the headers you are returning from lambda and headers you setup while enabling CORS on resource are equal.

In my case value of "Access-Control-Allow-Headers" returned from lambda function and "Access-Control-Allow-Headers" returned when hit the endpoint with OPTIONS method were not same.

while enabling CORS the default value is "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" but in lambda I was only returning "Content-Type". Making them equal resolved the issue.

Annabellannabella answered 3/10, 2023 at 13:55 Comment(0)
E
0

I was using a default DynamoDB lambda set up for basic CRUD access.

After correctly setting up the API Gateway (e.g., needed to accept * origin), it was set up to pass ALL request methods to the lambda.

The default lambda didn't have OPTION handling, so while it was sending the right headers, the lambda was sending a 400 error.

I had to add OPTIONS to its switch case, like so:


    try {
        switch (event.httpMethod) {
            case 'OPTIONS':
                // adding to allow "ALL" integration with API Gateway
                body = {};//await dynamo.delete(JSON.parse(event.body));
                break;
            case 'DELETE':
                body = await dynamo.delete(JSON.parse(event.body));
                break;
            case 'GET':
                body = await dynamo.scan({ TableName: event.queryStringParameters.TableName });
                break;
            case 'POST':
                body = await dynamo.put(JSON.parse(event.body));
                break;
            case 'PUT':
                body = await dynamo.update(JSON.parse(event.body));
                break;
            default:
                throw new Error(`Unsupported method "${event.httpMethod}"`);
        }
    } catch (err) {
        statusCode = '400';
        body = err.message;
    } finally {
        body = JSON.stringify(body);
    }

et voila. Took way too long to sort this.

Elevator answered 14/2 at 0:18 Comment(0)
P
-3

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.

Phosphoresce answered 29/1, 2019 at 11:59 Comment(0)
T
-4

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
    })
 }
Telfer answered 16/8, 2019 at 11:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.