Angular 如何触发。从服务器捕获状态400
当我从服务器获取状态代码400时,未触发捕获。。。也许有人能帮我 这是我的密码Angular 如何触发。从服务器捕获状态400,angular,client,try-catch,bad-request,Angular,Client,Try Catch,Bad Request,当我从服务器获取状态代码400时,未触发捕获。。。也许有人能帮我 这是我的密码 fetch('/api/orders/addOrder', { method: 'POST', mode: 'cors', cache: 'no-cache', credentials:'include', headers: { 'Content-Type': 'application/jso
fetch('/api/orders/addOrder', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials:'include',
headers: {
'Content-Type': 'application/json',
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
body: JSON.stringify(objToSend)
})
.catch(() => {
alert('all the orders on this date are taken. please choose another date')
});
无需发布我的服务器端代码,因为我知道在某些情况下,我肯定会获得此请求的状态代码400,但捕获不会触发任何想法?来自fetch api文档
fetch('your api url', {})
.catch((err)=> {
})
catch方法将捕获来自服务器的每个http错误
所以你可以把你的代码变成这样
fetch('/api/orders/addOrder', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials:'include',
headers: {
'Content-Type': 'application/json',
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
body: JSON.stringify(objToSend)
}).catch((err) => {
console.log(err);
}
);
function handleErrors(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
fetch('/api/orders/addOrder', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials:'include',
headers: {
'Content-Type': 'application/json',
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
body: JSON.stringify(objToSend)
})
.then(handleErrors)
.then(response => console.log("ok") )
.catch(error => console.log(error) );
这应该行得通
解决方案二
您可以使用es6链方法创建自己的处理程序
试试这样的
fetch('/api/orders/addOrder', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials:'include',
headers: {
'Content-Type': 'application/json',
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
body: JSON.stringify(objToSend)
}).catch((err) => {
console.log(err);
}
);
function handleErrors(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
fetch('/api/orders/addOrder', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials:'include',
headers: {
'Content-Type': 'application/json',
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
body: JSON.stringify(objToSend)
})
.then(handleErrors)
.then(response => console.log("ok") )
.catch(error => console.log(error) );