Trying to send an email through nodemailer using Firebase functions, but encountering errors. The data for the email will come from a form.
Error message: Access to XMLHttpRequest at 'my-firebase-functions' from origin 'my-angular-web-app' has been blocked by CORS policy due to no 'Access-Control-Allow-Origin' header presence on the requested resource.
Below is my Firebase functions configuration:
app.use((req, res, next) => {
// Define allowed origins
res.setHeader('Access-Control-Allow-Origin', 'https://stanleyogbonna-5228d.web.app');
res.setHeader('Access-Control-Allow-Origin', 'https://stanleyogbonna-5228d.firebaseapp.com');
// Define allowed HTTP methods
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Define allowed request headers
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,Content-Type');
// Allow credentials to be included in requests
res.setHeader('Access-Control-Allow-Credentials', true);
// Move to next layer of middleware
next();
});
// Gmail account credentials
const gmailEmail = functions.config().gmail.login;
const gmailPassword = functions.config().gmail.pass;
admin.initializeApp();
app.post('/visitor/contact', (req, res, next) => {
// Create transporter for sending emails
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: gmailEmail,
pass: gmailPassword
}
});
// Email content
const mailOptions = {
from: gmailEmail,
to: req.body.email,
subject: 'Full stack developer',
html: `<h1 style="color:blue;">Welcome ${req.body.firstName}</h1>
<p style="font-size:25px;">Thank you very much for contacting me. i hope you are
having a great time where ever you may be.</p>
<p style="font-size:25px;">I am a full stack developer by training and i am available at the moment for a MEAN stack job That will challenge me to be better.</p>
<p style="font-size:23px;">Thanks ${req.body.firstName}</p>`
};
transporter.sendMail(mailOptions);
})
// Handle 404 error
app.use((req, res, next) => {
next(createError(404));
});
// Error handler
app.use((err, req, res, next) => {
// Set error message and provide error details only in development mode
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// Render the error page
res.status(err.status || 500);
res.render('error');
});
exports.app = functions.https.onRequest(app);