我在页面上有一个表单,在填写字段时,我单击submit。它向后端发出Post API调用。我也希望从API调用中得到一些响应。我正在尝试弄清楚如何区分成功响应和错误响应。
例如,对于成功,我会得到以下响应。
{
"data": {
"attributes": {
//These are the fields and i display the field values on the page
"age": 32,
"sex": 'male'
}
}
}在API调用失败的情况下,我会得到以下响应
{
"errors": [
{
"status": "401",
"title": "Unauthorized request"
}
]
}即使有任何其他失败的原因,例如Unauthorized access或Internal server error,我也会在errors数组中得到它们各自的"status“和"title”,如上所示。
如何区分响应是成功还是失败,如果是失败,如何检查返回的失败状态。有没有人能帮我理解一下。
发布于 2020-11-02 11:37:45
您还可以添加两个操作-一个用于成功,另一个用于失败。
在Saga函数*中,添加try-catch块。在try中,在Api post call命令之后,可以请求成功动作。在catch中,您可以请求失败操作。
try {
const result = yield call(axios.POST, ....) // API Post call
yield put(actions.successAction(result))
} catch(error) {
yield put(actions.failAction(error))
}https://stackoverflow.com/questions/64639462
复制相似问题