2016-06-27 8 views
0

無効なログイン試行で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)); 
     }); 
    }; 
}; 
+0

'if(response.status!== 400)を返すのはなぜですか?response.json()。then(loginUserSuccess).then(dispatch)'? – Bergi

+0

@Bergiこのようなことが正しいアプローチだとお考えですか? http://pastebin.com/C2Bn65hd – manosim

+0

はい、正確には、[ディスパッチの重複を避けるために、エラーとしてjsonをスローする](http://stackoverflow.com/a/29475662/1048572) loginUserFailure(...)) ' – Bergi

答えて

1

あなたは重宝手動reject約束は、無効な応答コードが返されることができるかどうか。これは、catchコールバックによって処理されます。

The MDNには、Promise.reject()に関する詳細情報があります。

この例では、それが行うことができる方法を示しています。応答のいずれかのタイプで動作するように設計されているため

window.fetch APIを使用して
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); 
    }); 

Source, section Chaining Promises

+0

また、 'Fetch.response'オブジェクトには、それを拒否するかどうかを定義するのに役立つ' ok'プロパティがあります。 –

1

は、あなたのための非常に低レベルのようで、 JSONだけが必要です。

axiosなどのJSON解析を気にする別のライブラリを検討してください。

関連する問題