【发布时间】: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 路由,为什么会有一个请求。
感谢任何帮助!
【问题讨论】:
-
是浏览器自动发出的飞行前请求。 developer.mozilla.org/en-US/docs/Glossary/Preflight_request
标签: node.js express http http-headers fetch