简体   繁体   中英

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.

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
}));

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"}), )

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);

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM