【发布时间】:2017-10-31 01:29:28
【问题描述】:
问题
我觉得这是一个范围界定问题。我无法在 catch 块中返回。它总是返回成功。虽然 if 语句适用于失败部分(我使用 console.log 对其进行了调试)。
背景信息
有一个使用 laravel 的后端 API。在这段代码中,我登录 API 以使用 react-redux 获取 JWT 令牌。将来调用 API 需要此令牌。代码运行良好,并在实际成功时收到令牌,但我无法在失败时提前返回。
export function requestApiToken(username, password){
const url = ROOT_URL + 'user/login';
const request = axios.post(url, {
email: username,
password: password,
headers: {
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
}
})
.catch(function (error) {
//somehow it always returns an error
//currently 500=succes (will fix that later in api to 200)
if(error.response.status == 500){
console.log('succes')
console.log(error.response.data);
}else{
console.log('error')
console.log(error.response.data);
return{
type: FETCH_API_TOKEN_FAILURE,
token: null,
message: 'Please enter a valid e-mail and username for the API and try again'
}
}
});
return{
type: FETCH_API_TOKEN_SUCCES,
token: request, //should be error.response.data
message: 'Succesfull login'
}
}
编辑作为对评论部分的回应。
这是服务器返回的内容:
目前代码总是在代码块中返回 FETCH_API_TOKEN_SUCCES
正如答案中所建议的那样,我通过使用 redux-thunk 作为我的中间件而不是 redux-promise 来让它工作
在 index.js 中添加
import thunk from 'redux-thunk';
const createStoreWithmiddleware = applyMiddleware(thunk)(createStore);
在requestApiToken方法中
return(dispatch) => {
request.then(function (response) {
dispatch({
type: FETCH_API_TOKEN_SUCCESS,
token: response.data.token,
message: 'Successfull login'
})
});
request.catch(function (error) {
if(error.response.status == 422){
dispatch({
type: FETCH_API_TOKEN_FAILURE,
token: null,
message: 'Please enter a valid e-mail and username for the DiabetesAPI and try again'
})
}
});
dispatch({
type: FETCH_API_TOKEN_PENDING,
token: null,
message: 'Pending API Token request'
});
}
【问题讨论】:
-
尝试删除 if 语句只是为了调试目的
-
@AmrAly 我更新了我的问题,感谢您的帮助
-
我相信你会需要使用redux-thunk中间件。
-
Redux-thunk 解决了这个问题,感谢@AmrAly
标签: reactjs react-redux axios