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...
AllowedOrigin
allowCredentials
to true
.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"}),
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With