node.js - 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 路线,为什么会有一个请求。
任何帮助表示赞赏!
解决方案
如果您证明将代码 app.use 放在应用程序所有中间件的开头。
推荐阅读
- javascript - 全局样式不会覆盖阴影 dom 样式
- java - 为什么我可以为 Android AIDE 中的最终变量重新分配新值?
- javascript - 生产版本太大
- visual-studio-code - 我无法安装 Visual Studio Code
- css - NPM 引导程序和其他带有 Visual Studio 代码的程序
- julia - Julia typeof 的令人费解的结果
- ios - 顺利更新应用内 Apple 订阅定价
- javascript - 将新项目添加到两个不同的 ID
- javascript - 键盘在移动浏览器(iOS + Android)中失去焦点
- c++ - 如何模拟构造函数具有std :: string参数的类对象