如何在axios中获取响应状态码?标准解决方案无效。

3
我有一个axios的代码,但我无法获取响应状态码。这里有什么问题?例如,我得到的是'undefined'而不是201。
提前感谢!
  axios.post('endpoint', { body })
    .then((response) => {
        console.log(response.status);
    })

1
给一个 [mre];什么是 Api?它应该可以与 Axios 一起使用,除非你在某个地方进行了配置。 - jonrsharpe
@jonrsharpe 抱歉。已编辑。 - Robert Gurjiev
2个回答

3

如果出现错误,你必须捕获结果

axios.post('endpoint', { body })
    .then((response) => {
        // do something
    })
    .catch((error) => {
        console.log(error.response.status)
    })


我收到了500错误代码,并且在这种情况下.then内部的代码正在运行。 - Robert Gurjiev
2
在这种情况下,response.status 应该是可用的。你能分享一下响应对象吗? - Bruno Vasconcelos
对我来说,如果是404响应,那么响应只是“false”。 - nonNumericalFloat

0
    post(endpoint, body) {
        return axios.post(endpoint, body)
          .then((response) => {
            return { 
               error: null, 
               data: response.data, 
               status: response.status 
             };
          })
          .catch((error) => {
            return { error: error };
      });
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接