4

i am experiencing continuing problems with the CORS integration for API Gateway + Lambda. i have enabled CORs for the resources associated with the API. Everything appears to work fine via Lambda testing, Postman testing etc, but calling the api from a webpage script is giving the following error "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 415." Do I need to change the Lambda function? Thanks

Here is my simple Lambda code..

'use strict';
var AWS = require('aws-sdk');
var dclient = new AWS.DynamoDB.DocumentClient();
var getItems = (event, context, callback) => {

    var params = {
        TableName: "OMSCaseDataTest",
        Key: {
            "IncidentID": event.IncidentID
        }
    }
    dclient.get(params, (error, data) => {
        if (error) {
            callback(null, "error occured")
        } else {
            callback(null, data);

        }
    });
};
exports.getItems = getItems;
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Patrick
  • 41
  • 1
  • 2
  • 1
    please be careful when choosing the tags for your question. – bolov Feb 08 '18 at 15:51
  • How to setup CORS depends on the type of resource integration you're working with. It would be helpful if you clarified your question more. How have you tried setting up CORS? What kind of resource integration are you using? This document is helpful: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html – Daniel B. Feb 08 '18 at 19:49
  • Hi Daniel, thanks for the reply. I already enabled CORS in the API gateway (as per the AWS guidelines) and I can see the appropriate response headers within the Options response method i.e. Response Headers for 200: Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin. I have read in some threads that the Lambda function also has to be modified in some way, but can't find any clear instructions. – Patrick Feb 09 '18 at 09:04
  • I was about to ask a similar question as I was struggling with this. I decided to run my lambda express apps locally and found that there were actually internal runtime errors. I guess when an internal server error occurs, in lambda, API Gateway returns a CORS error? Also make sure you use `amplify function build` if you are using amplify before pushing updates. – SuperVeetz Feb 02 '19 at 22:46
  • Possible duplicate of [API Gateway CORS Issue](https://stackoverflow.com/questions/35277679/api-gateway-cors-issue) – Alex R Feb 15 '19 at 04:22

3 Answers3

4

If you are using proxy integration in API Gateway, then enabling CORS from API Gateway doesn't work. You have to set the Header 'Access-Control-Allow-Origin' from your Lambda code itself.

Its mentioned in the doc.

Python code sample:

response = {
    'statusCode': 200,
    'headers': {
        'Access-Control-Allow-Origin': '*'
    },
    'body': json.dumps({'message': 'CORS enabled')
}
return response
Dawn T Cherian
  • 4,968
  • 3
  • 24
  • 35
  • This is the correct answer, and was written before the other correct answer below. Can OP choose this if it is what worked for them? – Sinux1 Jul 18 '21 at 17:39
3

Assuming you're using proxy integration, you'll need to handle the CORS yourself. Your lambda function will need to handle the HTTP methods differently. CORS problems usually occur when the pre-flight option request is not entertained. Here's a code snippet could help your cause.

function main(event, context, lambdaCallback) {
    if (event.httpMethod === 'OPTIONS') {
        doneOptions(200, '{"status": "OK"}', 'application/json', lambdaCallback);
    } else if (event.httpMethod === 'POST') {
        // do your POST here
    } else {
        return done(400, '{"message":"Invalid HTTP Method"}', 'application/json', lambdaCallback);
    }
}

The functions that return the HTTP 200 to your frontend which decide what your frontend/API could call and what's not.

function doneOptions(statusCode, body, contentType, lambdaCallback, isBase64Encoded = false) {
    lambdaCallback(null, {
        statusCode: statusCode,
        isBase64Encoded: isBase64Encoded,
        body: body,
        headers: {
            'Content-Type': contentType,
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Headers': 'Authorization,Content-Type',
            'Access-Control-Allow-Method': 'GET,POST,OPTIONS',
        }
    });
}
xion
  • 1,209
  • 11
  • 17
1

Some times the lambda time out causes CORS error. You can increase the timeout this may fix the issue.

enter image description here