Skip to content
Advertisement

Firebase fuction returning “Response is not valid JSON object.”

I am trying to send emails from a firebase function that I call from my vue app. My firebase function looks like:

const functions = require('firebase-functions');
const admin = require("firebase-admin")
const nodemailer = require('nodemailer');

admin.initializeApp()


//google account credentials used to send email
var transporter = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 465,
    secure: true,
    auth: {
        user: 'xxxxx@gmail.com',
        pass: 'xxxxxxxxxx'
    }
});


exports.sendMail = functions.https.onRequest((req, res) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Content-Type");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    const mailOptions = {
        from: `•••••••••@gmail.com`,
        to: req.body.email,
        subject: 'contact form message',
        html: `<h1>Order Confirmation</h1>
                            <p>
                               <b>Email: </b>"hello<br>
                            </p>`
    };


    return transporter.sendMail(mailOptions, (error, data) => {
        console.log("here")
        if (error) {
            return res.send({"data": error.toString()});
        }
        data = JSON.stringify(data)
        return res.send({"data": `Sent! ${data}`});
    });

});

I removed the user and pass values here. They have the correct value in my code. The vue method I use to call this function looks like:

sendEmail(){
        let sendMail = firebase.functions().httpsCallable('sendMail');
        sendMail(
            {
                email: 'xx@xx.xx.xx'
            }
        ).then(
            result => {
                console.log(result.data)
            }
        )
    }

When this function is called I get the following error in the console:

Uncaught (in promise) Error: Response is not valid JSON object.
at new e (index.cjs.js:58)
at t.<anonymous> (index.cjs.js:543)
at u (tslib.es6.js:100)
at Object.next (tslib.es6.js:81)
at s (tslib.es6.js:71)

Any help would be appreciated. Thanks

Advertisement

Answer

You must a return a valid JSON result like this:

return res.status(200).json({});

Here the JSON is {} but it could be for instance something like {"status": "success}.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement