I have a react contact form, with a firebase cloud function handling sending an email with nodemailer and an axios post request to store the data in my firestore db. I am using CORS in my function, but am still getting the CORS error in my console when submitting the form.
Access to XMLHttpRequest at 'https://.cloudfunctions.net/submit' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I've spent about 2 hours googling and from what I've read it seems that if I have const cors = require('cors')({origin: true}); it should work. Any assistance would be great.
const functions = require('firebase-functions');
const nodemailer = require('nodemailer');
const cors = require('cors')({origin: true});
const gmailEmail = functions.config().gmail.email;
const gmailPassword = functions.config().gmail.password;
const mailTransport = nodemailer.createTransport({
service: 'gmail',
auth: {
user: gmailEmail,
pass: gmailPassword,
},
});
exports.submit = functions.https.onRequest((req, res) => {
cors(req, res, () => {
if (req.method !== 'POST') {
return;
}
const mailOptions = {
from: req.body.email,
replyTo: req.body.email,
to: gmailEmail,
subject: `${req.body.name} submitted a quote request!`,
text: req.body.message,
html: `<p>{req.body.message}</p>`,
};
mailTransport.sendMail(mailOptions).then(() => {
console.log('New email sent to:', gmailEmail);
res.status(200).send({ isEmailSend: true });
return;
});
});
});
// This snippet is in my contact.js component
const sendEmail = () => {
axios
.post(
'https://<myurl>.cloudfunctions.net/submit',
formData
)
.then((res) => {
db.collection('emails').add({
name: formData.name,
email: formData.email,
phone: formData.phone,
message: formData.message,
time: new Date(),
});
})
.catch((err) => {
console.log(err);
});
};
I deleted the cloud function and recreated it and I no longer had the cors issue.