【问题标题】:CORS preflight request error ExpressJS and AngularCORS 预检请求错误 ExpressJS 和 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]);
    }
  });
};

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

【问题讨论】:

    标签: node.js typescript express cors


    【解决方案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。
    猜你喜欢
    • 2015-08-10
    • 2019-04-11
    • 2016-09-19
    • 2017-05-06
    • 2018-11-28
    • 2020-04-09
    • 2016-07-06
    • 2021-08-25
    • 1970-01-01
    相关资源
    最近更新 更多