问题描述
我在 React 中使用 fetch
API,并从 JSON 端点提取一些数据.
I'm using the fetch
API in React, and I'm pulling down some data from a JSON endpoint.
作为我请求的一部分,我想发送一个自定义 User-Agent
字符串.目前,当我检查我的请求时,UA 字符串是:
As part of my requests, I want to send a custom User-Agent
string. Currently, when I inspect my requests, the UA string is:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
因为我在每个请求中都输入了标头,所以我想我只需将 User-Agent
附加到标头对象,就像它在 各种 地点在线:
Since I'm pasing in headers with every request, I figured I'd just append User-Agent
to the headers object, like it says in various places online:
fetch(url, {
Accept: 'application/json',
'Content-Type': 'application/json',
'User-Agent': 'MY-UA-STRING' // <---
})
但这不起作用.正如 here 报道的那样,我感觉这是因为 fetch api 中的错误 和 这里 和 这里.
But this doesn't work. I have a feeling it's becuase of a bug in the fetch api, as reported here and here and here.
任何人都可以解决如何使用 fetch
将 UA 作为 headers
的一部分传递?
Anyone have a work around on how to pass UA as part of the headers
using fetch
?
推荐答案
经过一些测试,Chrome确实存在User-Agent header的bug.
After some testing, Chrome does indeed have a bug with the User-Agent header.
这很可能是因为不久前(2015 年年中)User-Agent 标头在不允许的标头列表中.
This is most likely due to the fact that the User-Agent header was on the list of disallowed headers not too long ago (mid 2015).
由于此特定标头最近已从不允许标头列表中删除,Firefox(从版本 43 开始)将允许您在 fetch 调用中更改 User-Agent,但 Chrome 不会.
As this particular header was recently removed from the list of disallowed headers, Firefox (from version 43) will let you change the User-Agent in a fetch call, but Chrome won't.
这是 Firefox 错误和 Chromium 错误
首先不允许它的原因是,确实没有充分的理由使用 User-Agent 标头发送任意数据,它应该用于发送实际的 User-Agent 和浏览器内请求,例如无论如何,XMLHttpRequest 的获取确实没有充分的理由来欺骗用户代理.
The reason it was disallowed in the first place, was that there's really no good reason to use the User-Agent header to send arbitrary data, it should be used to send the actual User-Agent, and in-browser requests like Fetch of XMLHttpRequest should really have no good reason to spoof the User Agent anyway.
这个 bug 什么时候会在 Chrome 中修复是任何人的猜测,但这确实是一个 bug,因为不允许的头列表不再列出 User-Agent 头,当在 Fetch 的选项对象中指定时它应该会改变.
When the bug will be fixed in Chrome is anyones guess, but it is indeed a bug as the list of disallowed headers no longer lists the User-Agent header, and it should change when specified in the options object of Fetch.
作为旁注,您通常应该使用 Headers 创建标题接口,并将它们包含在 options 对象中 在 headers
键下
As a sidenote, you should generally be creating the headers using the Headers Interface, and include them in the options objects under the headers
key
let headers = new Headers({
"Accept" : "application/json",
"Content-Type" : "application/json",
"User-Agent" : "MY-UA-STRING"
});
fetch(url, {
method : 'GET',
headers : headers
// ... etc
}).then( ...
这篇关于发送自定义用户代理字符串以及我的标头(获取)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!