Javascript 如何从 Axios 中的 http 错误中获取状态代码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39153080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:16:43  来源:igfitidea点击:

How can I get the status code from an http error in Axios?

javascriptaxios

提问by Sebastian Olsen

This may seem stupid, but I'm trying to get the error data when a request fails in Axios.

这可能看起来很愚蠢,但是当 Axios 中的请求失败时,我正在尝试获取错误数据。

axios.get('foo.com')
    .then((response) => {})
    .catch((error) => {
        console.log(error) //Logs a string: Error: Request failed with status code 404
    })

Instead of the string, is it possible to get an object with perhaps the status code and content? For example:

除了字符串,是否有可能获得一个带有状态代码和内容的对象?例如:

Object = {status: 404, reason: 'Not found', body: '404 Not found'}

回答by Nick Uraltsev

What you see is the string returned by the toStringmethod of the errorobject. (erroris not a string.)

你看到的是对象的toString方法返回的字符串error。(error不是字符串。)

If a response has been received from the server, the errorobject will contain the responseproperty:

如果已收到来自服务器的响应,则该error对象将包含以下response属性:

axios.get('/foo')
  .catch(function (error) {
    if (error.response) {
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    }
  });

回答by danii

As @Nick said, the results you see when you console.loga JavaScript Errorobject depend on the exact implementation of console.log, which varies and (imo) makes checking errors incredibly annoying.

正如@Nick 所说,您console.log在 JavaScriptError对象时看到的结果取决于 的确切实现console.log,这会有所不同,并且 (imo) 使检查错误非常烦人。

If you'd like to see the full Errorobject and all the information it carries bypassing the toString()method, you could just use JSON.stringify:

如果您想查看完整Error对象及其绕过该toString()方法的所有信息,您可以使用JSON.stringify

axios.get('/foo')
  .catch(function (error) {
    console.log(JSON.stringify(error))
  });

回答by Tan

I am using this interceptors to get the error response.

我正在使用这个拦截器来获取错误响应。

const HttpClient = axios.create({
  baseURL: env.baseUrl,
});

HttpClient.interceptors.response.use((response) => {
  return response;
}, (error) => {
  return Promise.resolve({ error });
});

回答by Yan QiDong

With TypeScript, it is easy to find what you want with the right type.

使用 TypeScript,很容易找到合适的类型。

import { AxiosResponse, AxiosError } from 'axios'

axios.get('foo.com')
  .then(response: AxiosResponse => {
    // Handle response
  })
  .catch((reason: AxiosError) => {
    if (reason.response!.status === 400) {
      // Handle 400
    } else {
      // Handle else
    }
    console.log(reason.message)
  })

回答by Moses Schwartz

You can use the spread operator (...) to force it into a new object like this:

您可以使用扩展运算符 ( ...) 将其强制转换为一个新对象,如下所示:

axios.get('foo.com')
    .then((response) => {})
    .catch((error) => {
        console.log({...error}) 
})

Be aware: this will not be an instance of Error.

请注意:这不会是 Error 的实例。

回答by Dmitriy Nevzorov

This is a known bug, try to use "axios": "0.13.1"

这是一个已知的错误,尝试使用 "axios": "0.13.1"

https://github.com/mzabriskie/axios/issues/378

https://github.com/mzabriskie/axios/issues/378

I had the same problem so I ended up using "axios": "0.12.0". It works fine for me.

我遇到了同样的问题,所以我最终使用了 "axios": "0.12.0". 这对我来说可以。

回答by Dmytro Naumenko

There is a new option called validateStatusin request config. You can use it to specify to not throw exceptions if status < 100 or status > 300 (default behavior). Example:

validateStatus请求配置中有一个新选项。如果状态 < 100 或状态 > 300(默认行为),您可以使用它来指定不抛出异常。例子:

const {status} = axios.get('foo.com', {validateStatus: () => true})

回答by Emre Tapc?

In order to get the http status code returned from the server, you can add validateStatus: status => trueto axios options:

为了获取服务器返回的http状态码,可以validateStatus: status => true在axios选项中添加:

axios({
    method: 'POST',
    url: 'http://localhost:3001/users/login',
    data: { username, password },
    validateStatus: () => true
}).then(res => {
    console.log(res.status);
});

This way, every http response resolves the promise returned from axios.

这样,每个 http 响应都会解析从 axios 返回的承诺。

https://github.com/axios/axios#handling-errors

https://github.com/axios/axios#handling-errors

回答by Mendy

You can put the error into an object and log the object, like this:

您可以将错误放入一个对象并记录该对象,如下所示:

axios.get('foo.com')
    .then((response) => {})
    .catch((error) => {
        console.log({error}) // this will log an empty object with an error property
    });

Hope this help someone out there.

希望这可以帮助那里的人。