我正在为我的ReactJS API调用使用Cross fetch
有没有一种方法可以捕获400
401
&获取响应中的403
。
以下是使用提取的示例代码
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
.then(json => console.log(json))
您可以在给第一个then
:的回调中检查状态代码
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => {
if ([400, 401, 403].includes(response.status)) {
throw new Error('Response status was 400, 401, or 403!');
}
return response.json();
})
.then(json => console.log(json))
.catch(error => console.error(error))