-1

I am trying to deal with CORS for my frontend. On my local host (development environment) the given cors works fine. but when I deploy application to heroku it gives the given error.

Access to XMLHttpRequest at 'myHerokuURL' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

Here is the CORS that I am using.

app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', '*');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, Authorization, x-auth-token, content-type');
    res.setHeader('Access-Control-Allow-Credentials', false);
    next();
  }); 
Yasir Shahzad
  • 47
  • 1
  • 9

2 Answers2

0

You need to add cors like below,

const cors = require('cors');
app.use(cors());
anonymous
  • 1,499
  • 2
  • 18
  • 39
0

You need to set cors before setting routes in your main app.js file.

npm i --save cors

Also, you can set the cors to automatically change depending on your environment mode (e.g. development or production)

Here is an example of how I usually setup cors:

var corsUrl;

if (process.env.NODE_ENV === 'development') {
  corsUrl = process.env.LOCAL_URL  // http://localhost:8080
} else if (process.env.NODE_ENV === 'production') {
  corsUrl = process.env.DEPLOY_URL // http://myapp.com
}

app.use(cors({
  origin: corsUrl
}))

Note: Use https://myapp.com - If you are forcing secure protocol on your server.

And then set routes

app.use('/', indexRoutes)
admin.use('/', adminRoutes)

Cors Documentation - https://www.npmjs.com/package/cors Hope this helps.