CORS in Firebase Cloud Functions

Viewed 1302

I'm currently learning how to use new Cloud Functions for Firebase and I'm trying to implement SendGrid inside it. My problem is that I get the "No 'Access-Control-Allow-Origin'" error. I read that I need to use CORS.

So I looked to the Firebase documentation and examples and Firebase docs suggests to add CORS middleware inside the function, I've tried it but it's not working for me: https://firebase.google.com/docs/functions/http-events

Here is my code :

const functions = require('firebase-functions');
const cors = require('cors')({origin: true});

exports.sendEmail = functions.https.onRequest((req, res) => {

 cors(req, res, () => {

  var helper = require('sendgrid').mail;
  var fromEmail = new helper.Email(req.query.fromEmail);
  var toEmail = new helper.Email(req.query.toEmail);
  var subject = req.query.subject;
  var content = new helper.Content('text/plain', req.query.content);
  var mail = new helper.Mail(fromEmail, subject, toEmail, content);


  var sg = require('sendgrid')('MY_SECRET_KEY');
  var request = sg.emptyRequest({
    method: 'POST',
    path: '/v3/mail/send',
    body: mail.toJSON()
  });

  sg.API(request, function (error, response) {
    if (error) {
      console.log('Error response received');
      res.status(500).send('error');
    }
    console.log(response.statusCode);
    console.log(response.body);
    console.log(response.headers);
    res.status(200).send('ok');

  })
 })
});

What am I doing wrong? I would appreciate any help with this.

0 Answers
Related