Home > other >  Error CORS when i want redirecting localhost:4000 to localhost:3000
Error CORS when i want redirecting localhost:4000 to localhost:3000

Time:12-08

i have a project with react and nodejs. now, i authenticate user in localhost:4000 (my server) then redirect to localhost:3000/*

const loginHandler = async (req, res,next) => {

passport.authenticate("local",{
  successRedirect:'http://localhost:3000/dashboard',
  failureRedirect:'http://localhost:3000/login',
  failureFlash: true
})(req,res,next)
};

but retrun this error

Access to XMLHttpRequest at 'http://localhost:3000/login' (redirected from 'http://localhost:4000/login') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. loginForm.jsx:26 Error: Network Error

CodePudding user response:

Yes, ports are treated as different origins. When the request is tried it asks if it is ok to do so by requeting the Cross-Origin Resource Sharing policy. And as the error suggests, the server at :3000 did not provide an Access-Control-Allow-Origin header. This header should list the domains allowing to contact it, or use wildcard.

If you are using express, see the CORS middleware to make this easy: https://expressjs.com/en/resources/middleware/cors.html

  • Related