Backend and Frontend running on different port, 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:
- Allow the frontend as
AllowedOrigin
- Set
allowCredentials
totrue
. - Do not use a wildcard (*) for
AllowedOrigin
(again, if you are dealing with cookies/authentication). Useprotocol
,host
ANDport
[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);