Javascript fetch() 不发送标头?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45591594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
fetch() does not send headers?
提问by Rasto
I am sending POST request like this from browser:
我正在从浏览器发送这样的 POST 请求:
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
})
By the time the request reaches my back-end it does not contain X-My-Custom-Headernor Authorizationheader.
当请求到达我的后端时,它既不包含X-My-Custom-Header也不包含Authorization标头。
My back-end is Google Cloud function for Firebase (basically just Node.js endpoint) that looks like this:
我的后端是用于 Firebase 的 Google Cloud 函数(基本上只是 Node.js 端点),如下所示:
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)
...
}
The console log of that Google Cloud for Firebase function does not contain any X-My-Custom-Headernor Authorizationheader.
该 Google Cloud for Firebase 函数的控制台日志不包含任何X-My-Custom-Header或Authorization标头。
What is wrong?
怎么了?
Edit 1
编辑 1
So using dev tools in Chrome a checked that neither X-My-Custom-Headernor Authorizationheader is send from the browser... The questions now are: Why? How do I fix it?
因此,在 Chrome 中使用开发工具检查浏览器中既不发送X-My-Custom-Header也不Authorization发送标头...现在的问题是:为什么?我如何解决它?
Edit 2
编辑 2
More information about my app: It's React app. I have disabled service worker. I have tried to create Requestand specifically add headers using req.headers.append(). The headers still wouldn't send.
关于我的应用程序的更多信息:它是 React 应用程序。我有残疾服务人员。我尝试Request使用req.headers.append(). 标头仍然不会发送。
回答by Vasiliy Faronov
The same-origin policyrestricts the kinds of requests that a Web page can send to resources from another origin.
该同源策略限制种类的网页可以从其他产地发送到资源的请求。
In the no-corsmode, the browser is limited to sending “simple” requests — those with safelisted methodsand safelisted headersonly.
在no-cors模式下,浏览器仅限于发送“简单”请求——仅那些具有安全列表方法和安全列表标头的请求。
To send a cross-origin request with headers like Authorizationand X-My-Custom-Header, you have to drop the no-corsmode and support preflight requests (OPTIONS).
为了与像头发送跨域请求Authorization和X-My-Custom-Header,你必须放下no-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 OPTIONScheck.
“简单”和“非简单”请求之间的区别是出于历史原因。网页总是可以通过各种方式(例如创建和提交表单)来执行一些跨域请求,因此当 Web 浏览器引入了发送跨域请求的原则性方式(跨域资源共享,或 CORS)时,决定这种“简单”的请求可以免于飞行前OPTIONS检查。
回答by Damien
Firstly: Use an object instead of new Headers(..):
首先:使用对象而不是new Headers(..):
fetch('www.example.net', {
method: 'POST',
headers: {
'Content-Type': 'text/plain',
'X-My-Custom-Header': 'value-v',
'Authorization': 'Bearer ' + token,
}
});
Secondly: Good to know, headers are lowercased by fetch!!
其次:很高兴知道,标题是小写的fetch!!
Thirdly: no-corsmode limits the use of headers to this white list :
第三:no-cors模式将标题的使用限制在此白名单中:
AcceptAccept-LanguageContent-LanguageContent-Typeand whose value is (application/x-www-form-urlencoded,multipart/form-data,text/plain)
AcceptAccept-LanguageContent-LanguageContent-Type其值为 (application/x-www-form-urlencoded,multipart/form-data,text/plain)
That's why only your Content-Typeheader is sent and not X-My-Custom-Headeror Authorization.
这就是为什么只Content-Type发送您的标头而不发送X-My-Custom-Headeror 的原因Authorization。
回答by Frank R.
Can you try this?
你能试试这个吗?
fetch(serverEndpoint, {
credentials: 'include'
})
回答by Greeshma
I also had this same issue. I resolved it by removing 'no-cors' from javascript and adding the following in server side spring boot.
我也有同样的问题。我通过从 javascript 中删除“no-cors”并在服务器端 spring boot 中添加以下内容来解决它。
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity httpSecurity) throws Exception {
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
}
}
回答by Timmehlkk
1st: when you call headers in your exports.createCompany function, you have let headers = ['Headers: ']with a capital Hinstead of lowercase hwhich might cause errors. you also have a comma after token in the headers which shouldn't be there.
第一:当你在你的exports.createCompany 函数中调用headers 时,你有let headers = ['Headers: ']一个大写H而不是小写h,这可能会导致错误。在标头中的标记后也有一个逗号,它不应该在那里。
2nd: everytime i have used fetch requests in react native, the header:doesn't need the new Headerson it.
第二:每次我在 react native 中使用 fetch 请求时,header:都不需要new Headers它。
try this: fetch(serverEndpoint, {
method: 'POST',
mode: 'no-cors',
redirect: 'follow',
headers:{
'Content-Type': 'text/plain',
'X-My-Custom-Header': 'value-v',
'Authorization': 'Bearer ' + token
},
body: companyName
})
尝试这个: fetch(serverEndpoint, {
method: 'POST',
mode: 'no-cors',
redirect: 'follow',
headers:{
'Content-Type': 'text/plain',
'X-My-Custom-Header': 'value-v',
'Authorization': 'Bearer ' + token
},
body: companyName
})

