user6147554
user6147554

Reputation:

How to fix "CORS Policy" error when I tried to access AWS lambda with HTTP request?

I finally decided to try AWS lambda to create cool serverless function. For my first one, I decided to create a simple function which send a mail. I plan to be able to send it mail datas then my function will use them to send a mail. Good to know, my lambda have to be accessible from my website, I plan to call it from my front-end logic.

Unfortunately, I'm encountering a CORS policy issue when I tried to fire my lambda function from my website. However, everything works fine when I fire it from my CLI, with cURL.

I created my lambda function with the API-Gateway boilerplate. I'm a front-end developer, I know some traditional AWS services but I tried to use lambda function for the first time so I suppose that I have a problem with my configuration.

I would like to share with you my current lambda configuration. You could find it below:

Here my lambda design Here my lambda design

Here my API-Gateway configuration API-Gateway configuration

Here my Gateway Responses Gateway Responses

Furthermore, you could find below my lambda code and the error encountered everytime I tried to call my lambda.

const getRes = (status, body) => {
  return JSON.stringify({
    statusCode: status,
    headers: {
      "Content-Type": "text/plain",
      "Access-Control-Allow-Origin" : "*"
    },
    body,
  });
};

exports.handler = async (event, context, callback) => {
  if (event.body !== null && event.body !== undefined) {
    /*
    ** SEND MAIL WITH BODY PARAMS
    */
    const response = getRes(200, 'Mail sent');
    callback(null, response);
  } else {
    const response = getRes(500, 'Params missed');
    callback(null, response);
  }
};

Access to XMLHttpRequest at 'XXX' from origin 'YYY' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I tried to understand why I continue to encountering this issue without success. I suppose that I have a problem with my API-Gateway configuration but I couldn't find it.

Do you have an idea?

Thanks!

Upvotes: 2

Views: 2210

Answers (1)

MisterSmith
MisterSmith

Reputation: 3624

You need to configure API gateway to send CORS headers

Upvotes: 1

Related Questions