简体   繁体   中英

Can't get CORS to work with firebase function

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: 'somemail@gmail.com',
            pass: 'apassword'
        }
    });

    const mailOptions = {
        from: 'somemail@gmail.com',
        to: 'somemail@outlook.fr, somemail@hotmail.fr',
        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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM