내 애플리케이션에는 인증 토큰을 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);
});
그러나 토큰이 만료 된 경우 API는 401 오류를 반환 할 수 있습니다. 응답이 성공할 때만 상태가 설정되도록 가져 오기에서 제대로 처리하려면 어떻게해야합니까?
가져 오기 응답의 성공 / 오류를 처리하는 더 깨끗한 방법은 Response#ok
readonly 속성 을 사용하는 것입니다.
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
})
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다