0

I have this function deployed on google cloud:

const sgMail = require('@sendgrid/mail');
exports.sendEmail = async (req, res) => {
    // Ensure you set this environment variable from your setup
    sgMail.setApiKey("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    
    res.set('Access-Control-Allow-Origin', '*');
    res.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    res.set('Access-Control-Allow-Headers', 'Content-Type');

    const msg = {
        to: 'xxxxxxxxxxxx',
        from: 'xxxxxxxxxxxxxxxx',
        subject: req.body.subject,
        text: `${req.body.message}
                  
        ${req.body.email}
        ${req.body.phone}`,
    };
    try {
        await sgMail.send(msg);
        res.status(200).send('Email sent successfully');
    } catch (error) {
        console.error(error);
        if (error.response) {
            console.error(error.response.body);
        }
        res.status(500).send('Error sending email');
    }
};

And when I test from Postman the POST request works perfectly but when I deploy my code to my test site it throws:

blocked by CORS policy: Response to preflight request doesn't pass access control check No 'Access-Control-Allow-Origin' header is present on the requested resource.

Any ideas?

Michael C
  • 308
  • 1
  • 6

1 Answers1

0

You should check the accepted answer to this post. Since the error message you encounter is about "No-Access-Control-Allow-Origin header" and "preflight", its covered by the answer. If other CORS related issue came up and the accepted answer doesn't answer that, you can check the other answer with high upvote points.

Hope this helps.

Michael C
  • 308
  • 1
  • 6