Vlad Vinnikov
Vlad Vinnikov

Reputation: 1457

How to make lambda work with ajax?

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?

Upvotes: 1

Views: 1337

Answers (3)

jackko
jackko

Reputation: 7344

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.

Upvotes: 1

Benny Bauer
Benny Bauer

Reputation: 1065

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.

Upvotes: 0

Chris Love
Chris Love

Reputation: 3893

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

Upvotes: 2

Related Questions