【问题标题】:ExpressJS : Unexpected HTTP OPTIONS request status code 204ExpressJS:意外的 HTTP OPTIONS 请求状态代码 204
【发布时间】:2021-09-15 12:04:04
【问题描述】:

我在 ExpressJS 中遇到了一个非常奇怪的问题。当我使用 Insomnia(Postman 的模拟)请求我的 API 时,它工作正常,除了 'Content-Type' : 'application/json' 之外没有任何标题,它工作正常。

现在我尝试使用 fetch 从浏览器中获取数据:

const reponseCustomer = await fetch(url, {
                method : "POST",
                headers: {
                    'Accept' : 'application/json',
                    'Content-Type' : 'application/json',
                    'mode' : 'cors'
                },
                body : obj
            })

ExpressJS 路由签名:

router.post('/', async function(req, res, next)

并请求听众:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE");
  next();
})

所以在获取之后,在终端我得到以下日志:

[9:41 PM] 
    OPTIONS /api/auth/register 204 1.629 ms - 0
POST /api/auth/register 400 8.824 ms - -

我的问题是,如果我在整个项目中都没有 OPTIONS 路由,为什么会有一个请求。

感谢任何帮助!

【问题讨论】:

标签: node.js express http http-headers fetch


【解决方案1】:

如果您证明将代码 app.use 放在应用的所有中间件的开头。

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center。
猜你喜欢
  • 2016-03-22
  • 2018-09-08
  • 2016-10-28
  • 1970-01-01
  • 2020-04-05
  • 2019-01-30
  • 2018-07-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多