無効なログイン試行で400
を返すWeb APIを使用しています。ユーザーが間違った資格情報を使用してログインしようとすると、APIのようなものを返します。Redux、Fetch、catchする方法json()
{
"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));
});
};
};
'if(response.status!== 400)を返すのはなぜですか?response.json()。then(loginUserSuccess).then(dispatch)'? – Bergi
@Bergiこのようなことが正しいアプローチだとお考えですか? http://pastebin.com/C2Bn65hd – manosim
はい、正確には、[ディスパッチの重複を避けるために、エラーとしてjsonをスローする](http://stackoverflow.com/a/29475662/1048572) loginUserFailure(...)) ' – Bergi