In my application, I have a simple fetch for retrieving a list of users which sends over an authentication token to an API
fetch("/users", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
token: this.props.getUser().token
})
})
.then(res => res.json())
.then(users => this.setState({ users }))
.catch(err => {
console.error(err);
});
However, the API may return a 401 error if the token is expired. How do I handle it properly in the fetch so that the state is only set when the response is succesful?
A cleaner way to handle success/error of a fetch response would be to use the Response#ok
readonly property
https://developer.mozilla.org/en-US/docs/Web/API/Response/ok
fetch('/users').then((response) => {
if (response.ok) {
return response.json();
}
throw response;
}).then((users) => {
this.setState({
users
});
}).catch((error) => {
// whatever
})
res
inside callback function in your first .then
function contains a key called status
which holds the request status code.
const url = 'https://api.myjson.com/bins/s41un'; fetch(url).then((res) => { console.log('status code:', res.status); // heres the response status code if (res.status === 200) { return res.json(); // request successful (status code 200) } return Promise.reject(new Error('token expired!')); // status code different than 200 }).then((response) => console.log(response));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.