11

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.

Minjae Park
  • 223
  • 2
  • 12
  • I couldn't really find any answer to this problem for several days, they are going to be deployed in separate ports so merging isn't an option. It will be a huge help if anyone gives me any advise! thank you! – Minjae Park Feb 05 '19 at 09:34

4 Answers4

4

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
}));
Niros
  • 634
  • 5
  • 17
  • cors() is enabled at serverside already and it allows my frontend to make html api request. I thought that does the job. now the thing is that CORS prevent my server to redirect my frontend.. would putting header help? because frontend wants to block redirect from different source, and can I bypass that adding a header from the server side? – Minjae Park Feb 05 '19 at 09:46
  • CORS becomes totally meaningless if that is the case. – Minjae Park Feb 05 '19 at 09:52
  • I've edited the answer with the code snippet you should add to resolve the issue. Let's start with this and see if there's any additional error – Niros Feb 05 '19 at 09:52
  • Thank you for your quick reply. I applied the code but there nothing happened. It still has the same error message. – Minjae Park Feb 05 '19 at 09:59
  • hmm maybe try to add preflightContinue: true (added to the answer) – Niros Feb 05 '19 at 10:20
  • Maybe because I have 2 servers running for each backend and frontend? – Minjae Park Feb 05 '19 at 10:30
1

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"}),
)
mayo
  • 3,615
  • 1
  • 34
  • 41
0

use a CORS middleware like

var enableCORS = function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, token, Content-Length, X-Requested-With, *');
  if ('OPTIONS' === req.method) {
    res.sendStatus(200);
  } else {
    next();
  }
};
app.all("/*", function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, token, Content-Length, X-Requested-With, *');
  next();
});
app.use(enableCORS);
0

So I have been having this problem with backend and frontend on different ports and blocking each other requests.
The solution that worked for me is SETTING UP frontend proxy to the backend: Medium article.

To-do: Add "proxy":<backend_server_link> onto the frontend folder's package.json.

Harshit Ruwali
  • 820
  • 1
  • 9
  • 20
Bao Huynh Lam
  • 844
  • 3
  • 11