我的代码段如下
const url = 'https://someurl.com';
const options = {
method: 'POST',
url: url,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json;charset=UTF-8'
},
data: {
property_one: value_one,
property_two: value_two
}
};
const response = await axios(options);
const responseOK = response && response.status === 200 && response.statusText === 'OK';
if (responseOK) {
const data = await response.data;
// do something with data
}
我们是否需要同时检查 response.status 和 response.statusText ?此外,如果 response.data 具有来自后端的附加状态,例如:
{
"transactionId": "123456789",
"document": {
"documentId": "123456",
"status": "S"
}
}
我们是否需要检查状态为“ S” 。如果是,我们如何检查 response.status 和 response.statusText ?
?谢谢。
答案 0 :(得分:0)
您应该在trycatch
语句中处理请求和响应
请求:
try {
const res = await axios.post('url', body);
//continue with res.data
} catch (err) {
const error = err.response.data;
//throw alert or something
}
响应:
try {
//query
res.status(200).json(data);
} catch (err) {
//error
res.status(500).json('Server Error');
}