React Axios捕获未触发

时间:2017-08-28 17:12:56

标签: javascript reactjs axios

我正在尝试学习React,我正在与Axios合作进行XHR API调用。就像我所做的一切一样,首先要做的是阅读文档。我按照以下文档实现了XHR调用:https://github.com/svrcekmichal/redux-axios-middleware#dispatch-action

不知何故,当请求失败时,会触发.then()子句而不是.catch子句。

我对于出了什么问题愚蠢地打我的头,我无法理解。下面是我如何实施Axios:

App.js:

const client = axios.create({
  baseURL:'http://localhost:8080/api',
  responseType: 'json'
});

const axiosMiddle = axiosMiddleware(client)
const createStoreWithMiddleware = applyMiddleware(thunk, axiosMiddle)(createStore)

Component.js:

handleLogin(event) {
  const credentials = {
    username: this.state.username,
    password: this.state.password
  }
  this.props.login(credentials)
    .then((response) => {
      console.log(response)
      console.log('SUCCESS')
    })
    .catch((response) => {
      console.log('ERROR')
    })
}

Action.js:

export function login(credentials) {
  return {
    type: ['LOAD','AWESOME','OH_NO'],
    payload: {
      request: {
        url: '/login/',
        method: 'POST',
        data: {
          username: credentials.username,
          password: credentials.password
        }
      }
    }
  }
}

并且console.log输出:

HTTP Failure in Axios Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:87)
Root.jsx:82 {type: "LOAD,AWESOME,OH_NO_FAIL", error: {…}, meta: {…}}error: {data: "Network Error", status: 0}meta: {previousAction: {…}}type: "LOAD,AWESOME,OH_NO_FAIL"__proto__: Object
Root.jsx:83 SUCCESS

慢慢地我疯了,不知怎的,我不知道如何解决它。有人能帮帮我吗?

1 个答案:

答案 0 :(得分:1)

在component.js中,你的登录没有进行任何异步调用,相反,它只返回一个对象,那里不会发生错误,这就是为什么它总是会结束" SUCCESS"。并且console.log(响应)总是打印登录返回的对象。

因此,您应该实际执行异步请求,而不是简单地返回对象。实际执行请求的方法是dispatch(login(credentials))

顺便说一句,你得到的错误与登录无关,它发生在App.js的axios.create中。