Asri
Asri

Reputation: 325

Cloud Firebase Function works locally but doesnt work after deployment

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: '[email protected]',
        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 <[email protected]>",
        "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}');
  }

Upvotes: 0

Views: 563

Answers (1)

Asri
Asri

Reputation: 325

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":"[email protected]",
      "displayName":"Johnny",
      "from":"JaneDoe",
   }
}

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

Upvotes: 2

Related Questions