如何通过axios设置“ 403 Forbidden”代码响应消息?

时间:2019-05-08 05:53:52

标签: reactjs react-redux axios

我正在使用此JWT plugin使用令牌API:

它可以很好地处理200个状态代码。但是我该如何处理403禁止错误消息?当状态代码为403 Forbidden时,如何设置我的自定义错误消息?

loginAction.js文件

export const LoginAction = (FormData) => {
  return (dispatch) => {
    axios({
      method: 'post',
      headers: { 'Content-Type': 'application/json' } ,
      url: API,
      data: FormData,
      })
      .then(function (response) {
        localStorage.setItem('tpwToken', response.data.token);
        dispatch({
          type: 'SET_USER',
          user: response.data,
          message: response.data.message
      })
    })
    .catch(function(error){
      console.log(error.message)
    })
  }
}

loginReducer.js

export const loggedUserData = (state = initialState, action = {}) => {
  switch(action.type) {
    case "SET_USER":
      return {
        ...state,
        isAuthenticated: !isEmpty(action.user),
        user: action.user,
        message: action.message
      }

    default: return state  
  }
}

export default loggedUserData;

console error message enter image description here

2 个答案:

答案 0 :(得分:0)

在api响应中...您将检查网络调用(ajax调用)响应中的状态。

.then(function (response) {
    if(response.data.status === 403){
        // throw error or log it
    }
    ...rest of the code
})

答案 1 :(得分:0)

您可以从config选项中添加条件以检查状态代码。尝试这样的事情。

export const LoginAction = (FormData) => {
  return (dispatch) => {
    axios({
      method: 'post',
      headers: { 'Content-Type': 'application/json' } ,
      url: API,
      data: FormData,
      validateStatus: function (status) {
         if(status === 403){
             // do something
          }
       }
      })
      .then(function (response) {
        localStorage.setItem('tpwToken', response.data.token);
        dispatch({
          type: 'SET_USER',
          user: response.data,
          message: response.data.message
      })
    })
    .catch(function(error){
      console.log(error.message)
    })
  }
}