如果服务器的响应类型不正确,如何捕获错误?

时间:2019-01-14 10:31:10

标签: javascript axios es6-promise

当我向后端请求“ moduleData”(这是一个稍后将要映射的数据的json对象)时,响应有时可能是一个字符串,该字符串是带有以下内容的HTML页面:

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 <html>
   <head>
   </head>
   <body text="#000000">
     <h2>Agent done</h2>
   </body>
 </html>

{ responseType: 'json' }对象提供get()函数时,这种中断和捕获错误不是吗?

这是我的代码的外观:

  axios
    .get(url, { responseType: 'json' })
    .then(response => {
      console.log(response)
      newState = this.formatData(response.data, oldState)
      this.setState(newState, () => {
        if (this.state.sortState) {
          this.sortEntries()
        }
      })
    })
    .catch(err => {
      console.log('Catch error')
      console.log(err.response)
      this.setStatus({
        action: 'get',
        show: true,
        msg: languages[this.state.lang].moduleDataFail,
        code: 400,
        isError: true,
      })
    })

0 个答案:

没有答案