Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backend and Frontend running on different port, CORS error

I'm running backend and frontend on different port(8000,8001), I can't make res.redirect(...) from express server and the browser shows CORS error(Access to XMLHttpRequest at...).

This is MEVN(Mongo, Express, Vue, Nodejs) application, Vue frontend and express(nodejs) backend is running on different port. I implemented cors()on the backend and it makes it possible for my frontend to make requests (get, post)but the backend still can't redirect frontend page, using res.redirect("...") because it shows CORS error.

// Backend
var cors = require('cors');
app.use(cors())
...
function (req, res, next){  // some middleware on backend
  ...
res.redirect('http://urltofrontend');  // cause error


// Error msg on Chrome
Access to XMLHttpRequest at 'http://localhost:8001/' (redirected from 
'http://localhost:8000/api/login') from origin 'null' has been blocked 
by CORS policy: Request header field content-type is not allowed by 
Access-Control-Allow-Headers in preflight response.

I've already done implementing cors() and it allows my frontend to make http request to my backend and it works well. However, res.redirect( ...) from backend is blocked by CORS error.

like image 648
Minjae Park Avatar asked Feb 05 '19 09:02

Minjae Park


2 Answers

To resolve the CORS error in the browser you should add the following HTTP header to the response:

Access-Control-Allow-Headers: Content-Type

You can do that by adding the following code:

app.use(cors({
  'allowedHeaders': ['Content-Type'],
  'origin': '*',
  'preflightContinue': true
}));
like image 97
Niros Avatar answered Oct 17 '22 18:10

Niros


Just my two cents...


If you are dealing with authentication calls and using cookies for that you should configure CORS. And for that you have to remebmer:
  1. Allow the frontend as AllowedOrigin
  2. Set allowCredentials to true.
  3. Do not use a wildcard (*) for AllowedOrigin (again, if you are dealing with cookies/authentication). Use protocol, host AND port [Why].

A Golang example (using gorilla/handlers):

handlers.CORS(
    // allowCredentials = true
    handlers.AllowCredentials(),
    // Not using TLS, localhost, port 8080 
    handlers.AllowedOrigins([]string{"http://localhost:8080"}),
    handlers.AllowedMethods([]string{"GET", "POST", "PUT", "HEAD", "OPTIONS"}),
    handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization"}),
)
like image 38
mayo Avatar answered Oct 17 '22 17:10

mayo