I have been trying to get cors to working for the past 24 hours but it doesnt work. I have tried using the npm package cors in the app variable app.use(cors())
and also in a specific route e.g router.post('/', cors(),(req, res) => { ... }
and also using the longer way of using app.use , my code is below.
mailer.js [Route]
const express = require('express')
const nodemailer = require('nodemailer')
var mailerTransport = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
auth: {
user: 'user@gmail.com',
pass: 'password'
}
})
const router = express.Router()
router.post('/',(req, res) => {
const mailOptions = {
from: 'email@gmail.com', // sender address
to: 'email2@gmail.com', // list of receivers
subject: req.body.subject, // Subject line
html: `email sent`// plain text body
};
mailerTransport.sendMail(mailOptions, function (err, info) {
if(err)
{
...
}
else
{
...
}
});
})
module.exports = router;
server.js
app.use(bodyParser.json())
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
app.options('*', (req, res) => {
// allowed XHR methods
res.header('Access-Control-Allow-Methods', 'GET, PATCH, PUT, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
res.send();
});
next()
})
app.use("/mailer", mailer)