CORS 预检请求错误 ExpressJS 和 Angular

Posted

技术标签:

【中文标题】CORS 预检请求错误 ExpressJS 和 Angular【英文标题】:CORS preflight request error ExpressJS and Angular 【发布时间】:2020-10-26 05:59:18 【问题描述】:

我正在尝试使用 ExpressJS 后端创建一个简单的登录,只是为了测试它是如何工作的。 但由于某些奇怪的原因,我的 Angular 前端执行了 OPTIONS 调用并引发了 CORS 错误。

OPTIONS 调用的请求标头如下图所示。

我的 ExpressJS Cors 设置:

// There are 2 front-end applications, only the second is used now but it needs to work with both.
env.redirectURL = ['http://localhost:4200', 'http://localhost:5200'];

const app = express();
app.use(cors( credentials: true, origin: env.redirectURL ));

在下面的代码中,我创建了一个 JWT 令牌并使用重定向将其发送到前端。然后由于某种原因,这会在我的前端调用失败的“选项”请求。

export default (req: Request, res: Response) => 
  if (!req.user) 
    if (env.logging) console.error('No user found!');
    res.status(500).send();
    return;
  

  const expiresIn = 30 * 60 * 24 * 60000;

  jwt.sign(req.user, env.jwt.secret,  expiresIn , (err, token) => 
    if (err) 
      if (env.logging) console.error(err);
      res.sendStatus(500); // Handle Error Better
     else 
      res.cookie('token', token, 
        sameSite: false,
        httpOnly: true,
        secure: env.jwt.secure,
        expires: new Date(new Date().getTime() + expiresIn),
      );

      res.redirect(env.redirectURL[1]);
    
  );
;

我已经坚持了好几天了,几个月前我也尝试过同样的事情。我因为无法弄清楚这一点而感到愚蠢,这是我最后的手段。

【问题讨论】:

【参考方案1】:

不调试很难解决这个问题。

您可以尝试替换此代码吗?

// There are 2 front-end applications, only the second is used now but it needs to work with both.
env.redirectURL = ['http://localhost:4200', 'http://localhost:5200'];

const app = express();
app.use(cors( credentials: true, origin: env.redirectURL ));

通过

const allowedOrigins = ['http://localhost:4200', 'http://localhost:5200'];
app.use(cors(
    origin: function (origin, callback) 
        if (!origin) return callback(null, true);
        if (allowedOrigins.indexOf(origin) === -1) 
            const msg = 'The CORS policy for this site does not allow access from the specified Origin.';
            return callback(new Error(msg), false);
        
        return callback(null, true);
    ,
    credentials: true,
));

【讨论】:

它仍然有同样的错误,除了现在它也不能使用 Insomnia。

以上是关于CORS 预检请求错误 ExpressJS 和 Angular的主要内容,如果未能解决你的问题,请参考以下文章

CORS 预检选项请求的 403 错误。怎么修?

CORS:预检通过,主请求完成 w/200,但浏览器仍然有 Origin 错误

为啥 CORS 错误“对预检请求的响应未通过访问控制检查”?

即使没有发出预检请求,也会在 POST 请求中出现 CORS 错误

cors(cors 策略:对预检请求的响应未通过访问控制检查)角度 7 中的错误

Yii 和 Vue2 CORS 启用。服务器以 404 错误响应预检 OPTIONS 请求