【发布时间】:2018-06-24 07:14:26
【问题描述】:
返回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 或帮我找到另一种方法吗?
【问题讨论】:
标签: javascript fetch-api