[英]How can I get the status code from an HTTP error in Axios?
這可能看起來很愚蠢,但我試圖在 Axios 中請求失敗時獲取錯誤數據。
axios
.get('foo.example')
.then((response) => {})
.catch((error) => {
console.log(error); //Logs a string: Error: Request failed with status code 404
});
除了字符串,是否有可能獲得一個帶有狀態代碼和內容的 object? 例如:
Object = {status: 404, reason: 'Not found', body: '404 Not found'}
你看到的是error
對象的toString
方法返回的字符串。 ( error
不是字符串。)
如果從服務器接收到響應,則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);
}
});
使用 TypeScript,很容易找到你想要的正確類型。
這使一切變得更容易,因為您可以通過自動完成獲得該類型的所有屬性,因此您可以了解響應和錯誤的正確結構。
import { AxiosResponse, AxiosError } from 'axios'
axios.get('foo.example')
.then((response: AxiosResponse) => {
// Handle response
})
.catch((reason: AxiosError) => {
if (reason.response!.status === 400) {
// Handle 400
} else {
// Handle else
}
console.log(reason.message)
})
此外,您可以將參數傳遞給兩種類型,以告知您在response.data
中的期望,如下所示:
import { AxiosResponse, AxiosError } from 'axios'
axios.get('foo.example')
.then((response: AxiosResponse<{user:{name:string}}>) => {
// Handle response
})
.catch((reason: AxiosError<{additionalInfo:string}>) => {
if (reason.response!.status === 400) {
// Handle 400
} else {
// Handle else
}
console.log(reason.message)
})
正如@Nick 所說,您在console.log
一個 JavaScript Error
對象時看到的結果取決於console.log
的確切實現,這會有所不同並且(imo)使檢查錯誤非常煩人。
如果您想查看完整的Error
對象以及繞過toString()
方法攜帶的所有信息,您可以使用JSON.stringify :
axios.get('/foo')
.catch(function (error) {
console.log(JSON.stringify(error))
});
請求配置中有一個名為validateStatus
的新選項。 您可以使用它來指定當狀態 < 100 或狀態 > 300(默認行為)時不引發異常。 例子:
const {status} = axios.get('foo.example', {validateStatus: () => true})
您可以使用擴展運算符 ( ...
) 將其強制轉換為這樣的新對象:
axios.get('foo.example')
.then((response) => {})
.catch((error) => {
console.log({...error})
})
請注意:這不會是 Error 的實例。
我正在使用這個攔截器來獲取錯誤響應。
const HttpClient = axios.create({
baseURL: env.baseUrl,
});
HttpClient.interceptors.response.use((response) => {
return response;
}, (error) => {
return Promise.resolve({ error });
});
為了獲取服務器返回的http狀態碼,可以在axios選項中添加validateStatus: status => true
:
axios({
method: 'POST',
url: 'http://localhost:3001/users/login',
data: { username, password },
validateStatus: () => true
}).then(res => {
console.log(res.status);
});
這樣,每個 http 響應都會解析從 axios 返回的承諾。
整個錯誤只能使用 error.response 來顯示:
axios.get('url').catch((error) => {
if (error.response) {
console.log(error.response);
}
});
const handleSubmit = (e) => {
e.preventDefault();
// console.log(name);
setLoading(true);
createCategory({ name }, user.token)
.then((res) => {
// console.log("res",res);
setLoading(false);
setName("");
toast.success(`"${res.data.name}" is created`);
loadCategories();
})
.catch((err) => {
console.log(err);
setLoading(false);
if (err.response.status === 400) toast.error(err.response.data);//explained in GD
});
};
看控制台日志你就明白了
使用 Axios
post('/stores', body).then((res) => {
notifyInfo("Store Created Successfully")
GetStore()
}).catch(function (error) {
if (error.status === 409) {
notifyError("Duplicate Location ID, Please Add another one")
} else {
notifyError(error.data.detail)
}
})
您可以將錯誤放入一個對象並記錄該對象,如下所示:
axios.get('foo.example')
.then((response) => {})
.catch((error) => {
console.log({error}) // this will log an empty object with an error property
});
僅獲取錯誤不返回對象確實很奇怪。 在返回error.response 時,您可以訪問所需的大多數反饋信息。
我最終使用了這個:
axios.get(...).catch( error => { return Promise.reject(error.response.data.error); });
這嚴格提供了我需要的東西:狀態代碼(404)和錯誤的文本消息。
這是一個已知的錯誤,嘗試使用"axios": "0.13.1"
https://github.com/mzabriskie/axios/issues/378
我遇到了同樣的問題,所以我最終使用了"axios": "0.12.0"
。 這對我來說可以。
Axios. get('foo.example')
.then((response) => {})
.catch((error) => {
if(error. response){
console.log(error. response. data)
console.log(error. response. status);
}
})
這是我的代碼:為我工作
var jsonData = request.body;
var jsonParsed = JSON.parse(JSON.stringify(jsonData));
// message_body = {
// "phone": "5511995001920",
// "body": "WhatsApp API on chat-api.com works good"
// }
axios.post(whatsapp_url, jsonParsed,validateStatus = true)
.then((res) => {
// console.log(`statusCode: ${res.statusCode}`)
console.log(res.data)
console.log(res.status);
// var jsonData = res.body;
// var jsonParsed = JSON.parse(JSON.stringify(jsonData));
response.json("ok")
})
.catch((error) => {
console.error(error)
response.json("error")
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.