Axios에서 HTTP 오류로 인해 상태 코드를 얻으려면 어떻게 해야 합니까?
바보같이 보일 수도 있지만, Axios에서 요청이 실패했을 때 오류 데이터를 얻으려고 합니다.
axios
.get('foo.example')
.then((response) => {})
.catch((error) => {
console.log(error); //Logs a string: Error: Request failed with status code 404
});
문자열 대신 상태 코드와 내용을 가진 객체를 얻을 수 있을까요?예를 들어 다음과 같습니다.
Object = {status: 404, reason: 'Not found', body: '404 Not found'}
여기 보이는 것은 에 의해 반환된 문자열입니다.toString의 방법error물건.(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자바스크립트Error정확한 실장에 따라 목적지가 결정되다console.log(imo) 체크 오류는 매우 성가신 일입니다.
모든 것을 보고 싶다면Error오브젝트 및 오브젝트가 전송하는 모든 정보를toString()메서드는 JSON.stringify를 사용할 수 있습니다.
axios.get('/foo')
.catch(function (error) {
console.log(JSON.stringify(error))
});
라고 하는 새로운 옵션이 있습니다.validateStatus를 지정합니다.status < 100 또는 status > 300(기본 동작)의 경우 예외를 슬로우하지 않도록 지정할 수 있습니다.예제:
const {status} = axios.get('foo.example', {validateStatus: () => true})
스프레드 연산자를 사용할 수 있습니다(...)를 사용하여 다음과 같은 새로운 오브젝트에 강제로 삽입합니다.
axios.get('foo.example')
.then((response) => {})
.catch((error) => {
console.log({...error})
})
주의: 이것은 에러의 인스턴스가 아닙니다.
이 가로채기를 사용하여 에러 응답을 얻고 있습니다.
const HttpClient = axios.create({
baseURL: env.baseUrl,
});
HttpClient.interceptors.response.use((response) => {
return response;
}, (error) => {
return Promise.resolve({ error });
});
전체 오류는 다음과 같은 error.response를 사용해야만 표시됩니다.
axios.get('url').catch((error) => {
if (error.response) {
console.log(error.response);
}
});
서버로부터 반환된http 상태 코드를 취득하려면 , 다음의 순서를 실행합니다.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에서 반환된 약속을 해결합니다.
https://github.com/axios/axios#handling-errors
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)
}
})
오류만 가져오면 개체가 반환되지 않는 것은 정말 이상합니다.error.response를 반환하는 동안 필요한 대부분의 피드백에 액세스할 수 있습니다.
결국 이렇게 된 거야.
axios.get(...).catch( error => { return Promise.reject(error.response.data.error); });
상태 코드(404)와 에러 문자메시지 등, 필요한 정보를 얻을 수 있습니다.
다음과 같이 개체에 오류를 넣고 개체를 기록할 수 있습니다.
axios.get('foo.example')
.then((response) => {})
.catch((error) => {
console.log({error}) // this will log an empty object with an error property
});
알려진이므로, .사용해 보세요."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")
})
언급URL : https://stackoverflow.com/questions/39153080/how-can-i-get-the-status-code-from-an-http-error-in-axios
'source' 카테고리의 다른 글
| jQuery AJAX 교차 도메인 (0) | 2022.10.06 |
|---|---|
| 위반 장시간 실행 JavaScript 태스크에 xxms가 소요되었습니다. (0) | 2022.10.06 |
| "java - server"와 "java - client"의 실제 차이점은 무엇입니까? (0) | 2022.10.06 |
| 문자열에서 마지막으로 발생한 문자열 바꾸기 (0) | 2022.10.06 |
| where 문이 있는 대량 업데이트 mysql (0) | 2022.10.06 |