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
,也不包含授权
标头。
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
,也不包含授权
标题。
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
也不会授权
标头来自浏览器...现在的问题是:为什么?如何解决?
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?
有关我的应用的更多信息:它小号作出反应的应用程序。我已经禁用了服务人员。我尝试创建 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.
发送包含授权
和 X-My-Custom-Header $ c $等标题的跨源请求c>,你必须放弃
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),决定这样的简单请求可以免于预检选项
检查。
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屋!