Search code examples
amazon-web-servicesaws-lambdacorsaws-api-gatewaysendgrid

CORS Error on sending email using SendGrid, setup on AWS Lambda with API Gateway


I was trying to send email using SendGrid from my front end Vite application but was getting CORS error. I came to know that I need a server to make this code work so I created a function in AWS Lambda and attached with API Gateway. But it still gives me CORS error when I call that API route from my front end application which is hosted on AWS S3 Bucket.

Following is my Lambda function

const sgMail = require('@sendgrid/mail')
  
async function send(mailData){

    var response;
    
    sgMail.setApiKey('My API Key')
    const msg = {
      to: '[email protected]', // Change to your recipient
      from: '[email protected]', // Change to your verified sender
      subject: mailData.subject,
      text: 'From: '+mailData.name+ ' Email: '+mailData.email+' Message: '+mailData.message,
    }
    await sgMail
      .send(msg)
      .then(() => {
        response= 'Email Sent!'
      })
      .catch((error) => {
        response= error
      })
  
  return response;
    

};

exports.handler = async (event) => {
  
  var mailData=JSON.parse(event.body)
  
  var response= await send(mailData);
  
  
  
  return {
            statusCode: 200,
            body: response,
            headers: {
            "Access-Control-Allow-Headers" : "Content-Type",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "OPTIONS,POST"
            },
        };
  
  
}

And here is my front end code in my Vite Application

async sendEmail()
        {

            let vm = this

            let data = JSON.stringify({
                "name": vm.name,
                "email": vm.email,
                "subject": vm.subject,
                "message": vm.message
            });

            let config = {
                method: 'post',
                url: 'https://hfkjsdhf.execute-api.us-east-1.amazonaws.com/default/qiToHappinessSendMail',
                headers: {
                    'Content-Type': 'application/json'
                },
                data: data
            };

            axios(config)
                .then((response) => {
                    console.log(JSON.stringify(response.data));
                })
                .catch((error) => {
                    console.log(error);
                });

        }

Console log screenshot enter image description here

I am able to call this from Postman.

Your help or guidance would be appreciated. Thank you.


Solution

  •        path: /api/v1/,
           method: post,
           cors: true,
    

    i refered from https://www.serverless.com/blog/cors-api-gateway-survival-guide/