返回时出现错误 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
或者帮我找到另一种方法吗?
原文由 jbakker 发布,翻译遵循 CC BY-SA 4.0 许可协议
服务器应在服务器端使用 Access-Control-Expose-Headers 公开标头:
@sideshowbarker 评论 解释了为什么您可以在浏览器的网络面板中看到标头,但是当您这样做时收到
null
response.headers.get("Content-Length")
:您可以通过将其复制/粘贴到控制台来查看它的工作情况:
请注意, Headers.get 的返回值将是字节字符串,因此您必须将其转换为数字才能在数字表达式中使用它: