我使用的Web API将返回400
以进行无效的登录尝试。当用户尝试使用错误的凭据登录时,api将返回如下内容:
{
"non_field_errors": "Invalid credentials. Please try again".
}
我想要实现的是:当响应为400时,它应该返回json并使用dispatch(loginUserFailure(error))
发送它。当然,如果成功,它应dispatch(loginUserSuccess(json))
。在我的情况下,如果.then(json => {...}
有权访问响应对象,那将非常方便,但显然这是不可能的。
关于解决方法的任何想法或任何关于看什么的建议都会很棒!
export function loginUser(username, password) {
const options = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({username, password})
};
return (dispatch, getState) => {
return fetch('/api/accounts/login/', options)
.then(response => {
if (!response.ok) {
throw Error(response.statusText);
}
return response.json();
})
.then(json => {
// Check the response status here and dispatch respectively
// if (response.status !== 400) {
// dispatch(loginUserFailure(error));
// }
dispatch(loginUserSuccess(json));
})
.catch(error => {
dispatch(loginUserFailure(error));
});
};
};
答案 0 :(得分:1)
您可以 reject
手动承诺,如果返回无效的响应代码,这会派上用场。然后由catch
回调处理。
The MDN在Promise.reject()
上有更多信息。
此示例显示了如何完成:
function status(response) {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response)
} else {
return Promise.reject(new Error(response.statusText))
}
}
function json(response) {
return response.json()
}
fetch('users.json')
.then(status)
.then(json)
.then(function(data) {
console.log('Request succeeded with JSON response', data);
}).catch(function(error) {
console.log('Request failed', error);
});
答案 1 :(得分:1)
使用window.fetch API对您来说似乎非常低级,因为它可以用于任何类型的响应,但您只需要JSON。
考虑使用axios或其他库来处理JSON - 为您解析。