javascript 如何使用 fetch() 从请求中获取响应的内容长度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48266678/
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
How to get the content-length of the response from a request with fetch()
提问by jbakker
I was getting an error when returning response.json()when I would do a request with an empty response body, so I'm trying to just return an empty object when there is an empty body. The approach I was going for is to check the Content-Lengthheader of the response, however, somehow response.headers.get('Content-Length')somehow returns null. Here is my code:
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));
});
}
Could you maybe help me to find the Content-Lengthof the response or help me to find another approach?
你能不能帮我找到Content-Length答案或帮我找到另一种方法?
回答by Ori Drori
The server should expose the header using Access-Control-Expose-Headerson the server side:
服务器应在服务器端使用Access-Control-Expose-Headers 公开标头:
Access-Control-Expose-Headers: Content-Length
@sideshowbarker commentexplains why you can see the header in the network panel of the browser, but receive nullwhen you do response.headers.get("Content-Length"):
@sideshowbarker评论解释了为什么您可以在浏览器的网络面板中看到标题,但null在您这样做时会收到response.headers.get("Content-Length"):
Just because your browser receives the header and you can see the header in devtools doesn't mean your frontend JavaScript code can see it. If the response from a cross-origin request doesn't have an Access-Control-Expose-Headers: Content-Length response — as indicated in this answer — then it's your browser itself that will block your code from being able to access the header. For a cross-origin request, your browser will only expose a particular response header to your frontend JavaScript code if the Access-Control-Expose-Headers value contains the name of that particular header.
仅仅因为您的浏览器收到标题并且您可以在 devtools 中看到标题并不意味着您的前端 JavaScript 代码可以看到它。如果来自跨域请求的响应没有 Access-Control-Expose-Headers: Content-Length 响应 - 如本答案所示 - 那么是您的浏览器本身会阻止您的代码访问标头. 对于跨域请求,如果 Access-Control-Expose-Headers 值包含该特定标头的名称,则您的浏览器只会向您的前端 JavaScript 代码公开特定的响应标头。
You can see it working by copy/pasting this to the console:
您可以通过将其复制/粘贴到控制台来查看它的工作情况:
fetch("//stackoverflow.com").then(response => console.log(response.headers.get("content-length")))
回答by jbakker
I just solved my problem by just putting the response.json()in a try/catch-block and catching the error that occurs when I try to parse an empty body. This is not the ideal solution, but it works for me.
我刚刚解决了我的问题,只需将 放入response.json()try/catch-block 并捕获当我尝试解析空主体时发生的错误。这不是理想的解决方案,但对我有用。
回答by user1635430
Finally, you can keep your code clean and just write if (response.ok).
最后,您可以保持代码干净,只需编写if (response.ok).
回答by André DS
You can do it like this :
你可以这样做:
if (response.ok === true) {
if (response.getResponseHeader("Content-Length") === 0) return {};
return response.json();
}
Or more easily like this :
或者更容易像这样:
if (response.ok === true) {
if (response.length === 0) return {};
return response.json();
}
Is it ok for you ? :)
你没事吧?:)

