3

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.

KENdi
  • 7,576
  • 2
  • 16
  • 31
Zoomzoom
  • 189
  • 3
  • 13
  • 2
    Outbound service requests are not possible without setting up billing. Have you set up billing for your project? – Rohan Stark Jul 04 '17 at 12:05
  • Yes I have upgraded my account ! – Zoomzoom Jul 04 '17 at 12:05
  • Maybe [this answer] (https://stackoverflow.com/a/37765371/7626492) could help you – Rohan Stark Jul 04 '17 at 12:09
  • Thx for the link ! But do you know why my code doesn't work ? – Zoomzoom Jul 04 '17 at 12:28
  • No, I'm sorry :(. I don't have much experience with CORS. I'd have written an answer if I did. I just commented to try and help you with the bare, obvious minimum! – Rohan Stark Jul 04 '17 at 12:30
  • Thx a lot !! :) – Zoomzoom Jul 04 '17 at 12:31
  • @RohanStark what is the definition of outbound requests, does it also cover requests to https://iid.googleapis.com – Simon H Nov 26 '17 at 16:31
  • @Zoomzoom did u find a solution for this issue ? I having same problem! – MSaudi Nov 09 '20 at 09:09
  • @MSaudi exports.sendEmail = functions.https.onRequest((req, res) => { return cors(req, res, async () => { const { data } = req.body const msg = { to: data.emails, from: data.senderEmail, subject: data.subject, html: data.html, } await sgMail.send(msg) res.json({ result: 'ok' }) }) }) – Zoomzoom Feb 25 '21 at 11:32

0 Answers0