That's pretty simple, I have an API that returns HTTP 412 and JSON description of the error.
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"
}
Is it possible for me in my javascript (ES6) to fetch my url and get a grip on BOTH information that I need:
- HTTP code
- parsed Json
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);
If i parseJSON before headers, the response.status is not available anymore. If I parse header before json, i throw an exception BEFORE getting a chance to get my JSON body.
Is there a way to handle this ?