这很简单,我有一个返回HTTP 412和错误的JSON描述的API。
Status Code:412 PRECONDITION FAILED
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:8000
Access-Control-Expose-Headers:access-token, expiry, uid
Content-Length:224
Content-Type:application/json
Date:Wed, 09 Mar 2016 16:31:39 GMT
Server:Werkzeug/0.9.6 Python/3.5.1
{
"errors": {
"email": [
"This field is required."
],
"password": [
"String value is too short."
],
"password_confirmation": [
"doesn't match Password"
]
},
"status": "error"
}
我可以在我的javascript(ES6)中获取我的网址并抓住我需要的两个信息:
export function checkHttpStatus(response) {
console.log(response);
if (response.status >= 200 && response.status < 300) {
return response;
}
throw error;
}
export function parseJSON(response) {
return response.json();
}
return fetch(getRegisterUrl(), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
})
.then(checkHttpStatus)
.then(parseJSON);
如果我在标头之前解析了jSON,则response.status不再可用。 如果我在json之前解析头文件,那么在有机会获得我的JSON主体之前我会抛出异常。
有办法解决这个问题吗?