进行 Express 重定向时的 PassportJS Access-Control-Allow-Headers

PassportJS Access-Control-Allow-Headers when making Express redirect

我收到以下错误:

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 片段:

 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);
   }
 );

请记住,即使我设置了 Access-Control-Allow-* headers,此错误仍然存​​在。 Express 要重定向到的路径是 Angular2 路由,/#/partners.

我使用 Angular2 来重定向而不是 Node 服务器。

我没有重定向到节点服务器内的路径,而是返回了成功确认作为响应。当 Angular2 收到成功确认后,它会将应用程序路由到正确的位置。

我将 /login 修改为以下内容:

app.post("/login", cors(),
  passport.authenticate("local"),
    function(req, res){
      res.status(200).json(req.user);
});

注意 res.status(200).json(req.user); 只是 returns 用户对象。

调用 /login 的 Angular2 代码片段如下所示(请记住 loginUserUserService 中的一个函数,它调用 /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;
  });

请注意 this.router.navigate(['/partners']); 处理重定向到 /partners