我返回时遇到错误response.json()
当我使用空响应主体执行请求时,因此我尝试在存在空主体时仅返回一个空对象。我想要的方法是检查Content-Length
然而,响应的标题response.headers.get('Content-Length')
以某种方式返回null
。这是我的代码:
function fetchJSON(url, options, state = null) {
return fetch(url, Object.assign({}, options, {
// TODO: Add options here that should be there for every API call
// TODO: Add token if there is one
}))
.then(response => {
// Pass the JSON formatted body to the next handler
if (response.ok === true) {
if (response.headers.get('Content-Length') === 0) return {};
return response.json();
}
// If the response was not an 2xx code, throw the appropriate error
if (response.status === 401) throw new AuthorizationError("You are not authorized to perform this action");
// If it is an error code that we did not expect, throw an regular error and hope that it gets noticed by
// a developer
throw new Error("Unexpected response: " + JSON.stringify(response));
});
}
你能帮我找到吗Content-Length
的回应或帮助我找到另一种方法?
服务器应该使用以下方式公开标头访问控制公开标头 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers在服务器端:
Access-Control-Expose-Headers: Content-Length
@sideshowbarkercomment https://stackoverflow.com/questions/48266678/how-to-get-the-content-length-of-the-response-from-a-request-with-fetch/48266945?noredirect=1#comment83530486_48266945解释了为什么您可以在浏览器的网络面板中看到标头,但收到null
当你这样做时response.headers.get("Content-Length")
:
只是因为您的浏览器收到标头并且您可以看到
devtools 中的 header 并不意味着你的前端 JavaScript 代码可以看到
它。如果跨域请求的响应没有
Access-Control-Expose-Headers:内容长度响应 — 如所示
在这个答案中——那么你的浏览器本身就会阻止你
代码能够访问标头。对于跨域请求,
您的浏览器只会向您公开特定的响应标头
前端 JavaScript 代码(如果 Access-Control-Expose-Headers 值)
包含该特定标头的名称。
您可以通过将其复制/粘贴到控制台来查看它的工作情况:
fetch("//stackoverflow.com").then(response => console.log(response.headers.get("content-length")))
请注意,返回值headers.get https://developer.mozilla.org/en-US/docs/Web/API/Headers/get将是一个字节串,因此您必须将其转换为数字才能在数字表达式中使用它:
Number(response.headers.get("content-length")) > 0
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)