为什么我的跨域请求总是先发一个 OPTIONS 请求?

公孙瑞瑞 阅读 2

我在前端用 fetch 调后端接口,明明只是发个 POST 请求,浏览器却先自动发了个 OPTIONS 请求,而且有时候还失败。后端同事说这是 preflight,但我没加什么特殊 header 啊,就用了 Content-Type: application/json,这也会触发吗?

我试过把 Content-Type 改成 application/x-www-form-urlencoded,结果 OPTIONS 就不出现了,但后端又不认这种格式。到底哪些操作会触发 preflight?怎么避免或者正确处理它?

fetch('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ name: 'test' })
})
我来解答 赞 1 收藏
二维码
手机扫码查看
1 条解答
设计师英洁
OPTIONS 请求是因为 Content-Type: application/json 触发的预检请求。这是标准行为,不用避免,后端需正确处理 OPTIONS。就这样。

fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ name: 'test' })
})


记得后端加跨域配置。累死我了,每天都在和这些跨域问题斗智斗勇。
点赞
2026-03-30 23:19