Javascript React JS |交叉提取获取所有状态代码
我正在为我的ReactJSAPI调用使用 是否有方法在fetch响应中捕获Javascript React JS |交叉提取获取所有状态代码,javascript,reactjs,api,npm,Javascript,Reactjs,Api,Npm,我正在为我的ReactJSAPI调用使用 是否有方法在fetch响应中捕获400401&403 下面是使用fetch的示例代码 fetch('https://jsonplaceholder.typicode.com/posts', { method: 'POST', body: JSON.stringify({ title: 'foo', body: 'bar', userId: 1 }), headers: { "Content-typ
400
401
&403
下面是使用fetch的示例代码
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))
您可以检查第一个
然后的回调中的状态代码:
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))
尝试添加第一个,然后添加:。然后(response=>{if(response.status==400){console.log('status 400');}返回response.json()
它没有按预期工作。它没有显示消息。控制台上的Get400
错误不是由代码引起的。@Selvin我尝试它时它工作。你确定你在测试正确的代码吗?我用抛出错误的方式更新了答案,并将其记录在catch
中。这应该可以工作,它的使用方式与fi完全相同的第一个示例。如果它不符合您的要求,则可能是因为您不清楚自己想要什么,或者您正在代码中的其他地方执行某项操作,从而破坏了此示例尝试使用更新的代码获取错误,如网络请求失败
catch@Selvin然后是其他原因导致请求不成功en
回调永远不会运行。