透過 fetch 取得 server side 回傳的 json 之外, 如何處理伺服器回傳的錯誤代碼. 參考看看:
How to get Readable error response from JavaScript Fetch API?
https://stackoverflow.com/questions/40408219/how-to-get-readable-error-response-from-javascript-fetch-api
Check here https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
fetch(deafaultUrl + '/v1/users/',
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify(userInfoParams)
})
.then(function(response) {
console.log(response);
console.log(response.body);
console.log(response.message);
console.log(response.errors);
console.log(response.json());
dispatch(update_errors(response));
if (response.status >= 400) {
throw new Error("Bad response from server");
}
})
.then(function(json){
console.log("succeed json re");
// We can dispatch many times!
// Here, we update the app state with the results of the API call.
dispatch(update_user(json));
})
// here's the way to access the error message
.catch(function(error) {
console.log(error.response.data.message)
})
使用 response.status 可以拿到http 的 status code.
response.json() 可以拿到 json 內容. 但只能使用 .json() 一次,