I'm receiving the following error:
XMLHttpRequest cannot load http://localhost:4200/#/partners. Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
server.js snippet:
app.use(function(req, res, next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header('Access-Control-Allow-Credentials', "true");
next();
});
.
.
.
app.post("/login", function(req, res, next) {
passport.authenticate("local", function (err, user, info) {
if (err) { return next(err); }
if (!user){ return res.redirect(home_connection+'/#/'); }
req.logIn(user, function(err){
if(err){ return next(err); }
return res.redirect(home_connection+"/#/partners");
});
})(req, res, next);
}
);
Keep in mind that this error still persists even after I set the Access-Control-Allow-* headers. The path that Express is to redirect to is an Angular2 route, /#/partners.
I used Angular2 to redirect instead of the Node server.
Rather than redirecting to the path within the Node server, I just returned a success confirmation as the response. When Angular2 receives the success confirmation it then routes the app to the proper location.
I modified /login to the following:
app.post("/login", cors(),
passport.authenticate("local"),
function(req, res){
res.status(200).json(req.user);
});
Notice res.status(200).json(req.user); simply returns the user object.
The snippet of Angular2 code that calls /login looks like (keep in mind loginUser is a function in UserService that calls posts to /login):
this.userService
.loginUser(this.user.phone, this.third.value.code.replace(/ /g, ''))
.then((resp) => {
if(resp) this.router.navigate(['/partners']);
else {
this.third.setValue({"code":""});
this.invalidCode = true;
}
}).catch((err) => {
this.invalidCode = true;
});
Note that this.router.navigate(['/partners']); handles the redirection to /partners.