【问题标题】:Express middleware blocked by CORS policy (hitting authorization error for preflight OPTIONS request)Express 中间件被 CORS 策略阻止(预检 OPTIONS 请求遇到授权错误)
【发布时间】:2020-11-25 21:21:01
【问题描述】:

当这个块不存在时,我的 API 可以正常工作。

当我添加这个块时,我得到一个 CORS 错误:

对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。

我错过了什么?

app.use((req, res, next) => {
  try {
    if (secret !== config.secret) {
      throw new Error('Not Authorized')
    } else {
      next()
    }
  } catch (err) {
    next(err)
  }
});

【问题讨论】:

  • 消除了 CORS 错误。谢谢!

标签: node.js express cors authorization preflight


【解决方案1】:

如果请求的方法是OPTIONS,请确保不抛出错误:

if (req.method !== "OPTIONS" && secret !== config.secret) {
  throw ...
}

https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request

【讨论】:

    猜你喜欢
    • 2022-01-14
    • 1970-01-01
    • 2019-11-02
    • 2019-11-30
    • 2019-10-01
    • 1970-01-01
    • 2019-09-16
    • 2019-11-18
    • 2021-02-28
    相关资源
    最近更新 更多