0
votes

I'm trying for days now to send a valid redirect request in my App. What should happen: If I try to perform an action that requires me to be logged in, my express app should redirect to the login URL.

router.use(function(req,res,next){
    if(req.session.user == null){
        res.redirect('http://localhost:4200/#/login');
    }
    else
        next();
});

My CORS implementation:

var corsOptions = {
  origin:  process.env.ctxCliente,
  credentials: true
}
app.use(cors(corsOptions));

The error:

XMLHttpRequest cannot load http://localhost:4200/#/login. Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'null' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

On my Angular App I'm sending {withCredentials: true} with all requests, because I need to use a cookie to verify the user session id

1
If all of this happens within your app, then why is this a cross-domain request in the first place?CBroe
@CBroe My express app is on port 3000 and my Angular app is on port 4200julianomontini
Well the error message tells you what is basically wrong - you need to send a more specific Access-Control-Allow-Origin response to the preflight request in such a case, than just *.CBroe
In my corsOptions the origin is specified. process.env.ctxCliente is 'localhost:4200'julianomontini
Try using origin: true in corsOptionssideshowbarker

1 Answers

0
votes

After a lot of trial and error I solved the problem: Angular should intercept https request and check for redirects. Here is how an interceptor can be implemented: https://angular.io/guide/http#intercepting-all-requests-or-responses