fetch() 不发送标头? [英] fetch() does not send headers?
问题描述
我正在从浏览器发送这样的 POST 请求:
I am sending POST request like this from browser:
fetch(serverEndpoint, {
method: 'POST',
mode: 'no-cors', // this is to prevent browser from sending 'OPTIONS' method request first
redirect: 'follow',
headers: new Headers({
'Content-Type': 'text/plain',
'X-My-Custom-Header': 'value-v',
'Authorization': 'Bearer ' + token,
}),
body: companyName
})
当请求到达我的后端时,它既不包含 X-My-Custom-Header
也不包含 Authorization
标头.
By the time the request reaches my back-end it does not contain X-My-Custom-Header
nor Authorization
header.
我的后端是用于 Firebase 的 Google Cloud 函数(基本上只是 Node.js 端点),如下所示:
My back-end is Google Cloud function for Firebase (basically just Node.js endpoint) that looks like this:
exports.createCompany = functions.https.onRequest((req, res) => {
let headers = ['Headers: ']
for (let header in req.headers) {
headers.push(`${header} : ${req.headers[header]}`)
}
console.log(headers)
...
}
该 Google Cloud for Firebase 函数的控制台日志不包含任何 X-My-Custom-Header
或 Authorization
标头.
The console log of that Google Cloud for Firebase function does not contain any X-My-Custom-Header
nor Authorization
header.
怎么了?
所以在 Chrome 中使用开发工具检查了 X-My-Custom-Header
和 Authorization
标头都没有从浏览器发送......现在的问题是:为什么?我该如何解决?
So using dev tools in Chrome a checked that neither X-My-Custom-Header
nor Authorization
header is send from the browser... The questions now are: Why? How do I fix it?
关于我的应用的更多信息:它是 React 应用.我有残疾服务人员.我尝试创建 Request
并使用 req.headers.append()
专门添加标题.标头仍然不会发送.
More information about my app: It's React app. I have disabled service worker. I have tried to create Request
and specifically add headers using req.headers.append()
. The headers still wouldn't send.
推荐答案
同源政策 限制网页可以向来自另一个来源的资源发送的请求类型.
The same-origin policy restricts the kinds of requests that a Web page can send to resources from another origin.
在 no-cors
模式,浏览器仅限于发送简单"请求——那些带有安全列表的请求方法 和安全列表头.
In the no-cors
mode, the browser is limited to sending "simple" requests — those with safelisted methods and safelisted headers only.
要发送带有 Authorization
和 X-My-Custom-Header
等标头的跨域请求,您必须删除 no-cors
模式并支持预检请求(OPTIONS
).
To send a cross-origin request with headers like Authorization
and X-My-Custom-Header
, you have to drop the no-cors
mode and support preflight requests (OPTIONS
).
简单"和非简单"请求之间的区别是出于历史原因.网页总是可以通过各种方式(例如创建和提交表单)执行一些跨域请求,因此当 Web 浏览器引入了发送跨域请求的原则性方式时(跨域资源共享,或 CORS),因此决定此类简单"请求可以免于预检OPTIONS代码>检查.
The distinction between "simple" and "non-simple" requests is for historical reasons. Web pages could always perform some cross-origin requests through various means (such as creating and submitting a form), so when Web browsers introduced a principled means of sending cross-origin requests (cross-origin resource sharing, or CORS), it was decided that such "simple" requests could be exempt from the preflight OPTIONS
check.
这篇关于fetch() 不发送标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!