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,为什么会在OPTIONS路线上提出请求。

感谢您的帮助!

如果你想把你的代码app.use放在应用程序的所有中间件的开头。

最新更新