首页 > 解决方案 > ExpressJS:意外的 HTTP OPTIONS 请求状态代码 204

问题描述

我在 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.jsexpresshttphttp-headersfetch

解决方案


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


推荐阅读