Home > Software engineering >  Can't get CORS to work with firebase function
Can't get CORS to work with firebase function

Time:02-07

I've been trying to deploy a function to send me an email via a click on my website, but I can't get CORS to work, I've tried a lot, a LOT of things. The weirdest thing is that a lot of the time it works on the google cloud console test and on reqbin but the most i've been able to accomplish with my website is getting an error, somehow the mail gets through but with no content.

If you are wondering what kind of error I get, well I've basically done them all depending on what I've tried but the classic is :

Access to XMLHttpRequest at 'https://us-central1-myproject.cloudfunctions.net/send_mail' from origin 'https://myproject.web.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Function:

const functions = require('firebase-functions');

const nodemailer = require("nodemailer");

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

    res.set('Access-Control-Allow-Origin', '*');
    res.set('Access-Control-Allow-Headers', '*');
    res.set('Access-Control-Allow-Methods', 'GET, OPTIONS, POST');

    let data = req.body;

    const transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: '[email protected]',
            pass: 'apassword'
        }
    });

    const mailOptions = {
        from: '[email protected]',
        to: '[email protected], [email protected]',
        subject: data.subject,
        text: data.text
    };

    transporter.sendMail(mailOptions, function(error, info){
    if (error) {
        console.log(error);
        res.status(400).send('Échec');
    } else {
        console.log('Email sent: '   info.res);
        res.status(200).send('Succès');
    }
    });
});

Client side:

function send_email() {

    let sujet = document.getElementById("sujet").value;
    let texte = document.getElementById("corps").value;

    if (texte == "" && sujet == ""){
        window.alert("Veuillez remplir les champs");
        return;
    }
    if (sujet == ""){
        window.alert("Veuillez remplir le champ \"Sujet\"");
        return;
    }
    if (texte == ""){
        window.alert("Veuillez remplir le champ \"Message\"");
        return;
    }

    let xhr = new XMLHttpRequest();
    xhr.open("POST", "https://us-central1-myproject.cloudfunctions.net/send_mail");

    xhr.setRequestHeader("Content-Type", "application/json");

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
           console.log(xhr.status);
           console.log(xhr.responseText);
        }   
    };

    let data = `{
    "subject": "",
    "text": ""
    }`;

    let json = JSON.parse(data);
    json.subject = sujet;
    json.text = texte;  

    xhr.send(json);
}

I have also tried the CORS middleware and express

Any help would be greatly appreciated, thanks.

CodePudding user response:

Turns out the problem wasn't in the function like i thought, it was XMLHttpRequest. Switched to node fetch and everything works just fine.

const body = {
            "subject": "" sujet "",
            "text": "" texte ""
            };

        const response = await fetch('https://us-central1-myproject.cloudfunctions.net/send_mail', {
            method: 'post',
            body: JSON.stringify(body),
            headers: {'Content-Type': 'application/json'}
        });

        const res = await response.json();
  •  Tags:  
  • Related