1

I get 403 forbidden when making ajax request to lambda endpoint. It's likely to be a CORS Issue.

serverless.yml

    service: aws-nodejs # NOTE: update this with your service name
    provider:
    name: aws
    runtime: nodejs4.3

    functions:
    weather:
        handler: handler.weather
        events:
            - http:
                path: weather
                method: get
                cors: true

handler.js

'use strict';

    var request = require('request');

    module.exports.weather = (event, context, callback) => {
        request('http://api.openweathermap.org/data/2.5/weather?APPID=__ID__&lat=40.66&lon=-73.77', function (error, response, body) {
            if (!error && response.statusCode == 200) {
                const response = {
                    statusCode: 200,
                    headers: {
                        "Content-Type": "application/json",
                        "Access-Control-Allow-Origin": "*"
                    },
                    body: body
                };
                callback(null, response);
            }
        });
    };

```

I tried to enable CORS in API gateway, but I get invalid response code error.

enter image description here

Can you suggest how to fix the error and what could be causing it?

1
  • What is the error message you get? Hover the red exclamation mark Commented Dec 11, 2016 at 8:21

3 Answers 3

2

make sure you deploy the API once you make any changes, like adding CORS. I have been bitten by this several time.

Sign up to request clarification or add additional context in comments.

Comments

1

If you're using HTTP or Lambda 'proxy' integration, the non-OPTIONS method will have to return the relevant CORS headers (in this case Access-Control-Allow-Origin). The two errors you see there in the console are ok if you're using a proxy integration on the GET method. Configure the backend to send back the Access-Control-Allow-Origin header and try again.

Comments

0

If you're using the Serverless Framework you can easily do it by specifying cors: true under your function's http event:

functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: user/create
          method: get
          cors: true

You can find more details in the docs.

1 Comment

The header "Access-Control-Allow-Origin" : "*" is showing up in the browser, but it's not returning the header when I make AJAX call

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.