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
How can I get the status code from an http error in Axios?
提问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 toString
method of the error
object. (error
is not a string.)
你看到的是对象的toString
方法返回的字符串error
。(error
不是字符串。)
If a response has been received from the server, the error
object will contain the response
property:
如果已收到来自服务器的响应,则该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.log
a JavaScript Error
object 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 Error
object 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 validateStatus
in 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 => true
to 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 返回的承诺。
回答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.
希望这可以帮助那里的人。