0

I am writing my first Cloud Function which works great locally but doesn't work the moment I deployed it to Firebase. I am trying to invoke a Cloud function which will send an email via a HTTP request using Flutter Web. I read online and suspect it might be be because I cant return the promise. How do I ensure the asynchronous calls to be completed?

const nodemailer = require('nodemailer');
const cors = require('cors')({origin: true});

/**
* Here we're using Gmail to send
*/
let transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: 'dummyaccount@gmail.com',
        pass: 'dummypassword'
    }
});

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

        return transporter.sendMail(req.body, (erro, info) => {
            if(erro){
                return res.send(erro.toString());
            }
            return res.send('Message send');
        });
    });
});


const admin = require('firebase-admin');
admin.initializeApp();



This is my Http Request using Dart for Flutter Web
void httpCallFunction() async {
    var url =
        'https://us-central1-fire-station-ope-blablala.cloudfunctions.net/sendMail';
    var response = await http.post(
      url,
      body: json.encode({
        "from": "Dummy Guy <Do-Not-Reply@gmail.com>",
        "to": "$_email",
        "subject": "Your Booking has been approved!!",
        "html": approvedMessageTosent,
      }),
      headers: {
        'Content-type': 'application/json',
      },
    );
    print('Response status: ${response.statusCode}');
    print('Response body: ${response.body}');
  }
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Asri
  • 315
  • 3
  • 13
  • 2
    Do you get any error on the cloud functions logs? Also, what does these `console.log` at your flutter functions outputs? – Ralemos Aug 28 '20 at 12:48
  • I was faced with status code 204 and the console said Request body is missing data – Asri Aug 29 '20 at 18:46

1 Answers1

2

I went through a rollercoaster to solve this issue. So apparently the cloud function log came back with status code 204 and said that my 'Request body is missing data' but I could see that my data was being sent.

So I found another guy faced the exact same issue as I did in this link: Dart json.encode is not encoding as needed by Firebase Function

Essentially I had to wrap my data in a key called 'data'.

{
   "data":{ 
      "to":"john@doe.com",
      "displayName":"Johnny",
      "from":"JaneDoe",
   }
}

https://firebase.google.com/docs/functions/callable-reference#request_body

Asri
  • 315
  • 3
  • 13