1

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)

AN DI LE
  • 96
  • 3

2 Answers2

1

First install npm install cors for your node application. and make following changes in server.js

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())
Vikash Sharma
  • 204
  • 1
  • 8
  • thank you, unfortunately I have tried using that like I specified in my question but it did not work – AN DI LE Mar 19 '19 at 13:08
0

First you have to install npm package for cors as "npm install cors --save". In app.js file declare "var cors = require("cors");" and after that use "app.use(cors());". I think its work for you.

user3484089
  • 95
  • 10
  • thank you, unfortunately I have tried using that like I specified in my question but it did not work – AN DI LE Mar 19 '19 at 13:08