반응형
404 응답에서 엑시스로 오류 메시지를 캐치하거나 javascript로 가져옵니다.
api(https://rickandmortyapi.com)의 404 응답을 악시오로 지원하려고 합니다.
따라서 항목이 존재할 때 반응은 다음과 같습니다.
{
"data": {
"id": 11,
"name": "Albert Einstein",
// ...
},
"status": 200,
"statusText": "OK",
"headers": {
"content-type": "application/json; charset=utf-8"
},
"config": {
"transformRequest": {},
"transformResponse": {},
// ...
},
"request": {}
}
찾을 수 없는 응답은 404이며 데이터는 다음과 같습니다.
{
"error": "Character not found"
}
그래서 이 에러 메시지를 읽고 변수에 넣지만 효과가 없습니다.테스트용으로는 다음과 같은 것이 있습니다.
new Vue({
el: "#app",
data: {
existingCharacter: {},
nonExistingCharacter: {}
},
methods: {
apiRequest (id, character) {
console.log('starting Request');
axios('https://rickandmortyapi.com/api/character/'+id, {
validateStatus: function (status) {
return status < 500; // Reject only if the status code is greater than or equal to 500
})
.then((res) => {
console.log('got response');
console.log(res);
this[character] = res;
}
).catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
})
.then(function () {
console.log('request finished');
});
}
}
})
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.4/css/bulma.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div class="columns is-mobile">
<div class="column is-half">
<h2 class="title">existing item: </h2>
<button class="button is-fullwidth"
@click="apiRequest(11, 'existingCharacter')">
get
</button>
<pre>{{existingCharacter}}</pre>
</div>
<div class="column is-half">
<h2 class="title">non existing item:</h2>
<button class="button is-fullwidth"
@click="apiRequest(1123, 'nonExistingCharacter')">
get</button>
<pre>{{nonExistingCharacter}}</pre>
</div>
</div>
</div>
보시다시피 서버가 404로 응답했을 때 응답이 없습니다.404 회답에서 이 메시지를 읽을 수 있는 팁이 있나요?
이것도 fetch로 해봤는데 문제는 마찬가지인 것 같아요.서버가 404를 반환할 때 오류가 있을 뿐 그 이상은 없습니다.그 메시지를 404로 회신하는 것이 좋은 방법인가요?404에서는 콘솔에 CORS 메시지가 있는 것도 알 수 있습니다(이것이 열쇠일지도 모릅니다).
도와주셔서 감사합니다.:)
Rick and Morty API의 제한 사항입니다.요구가 404를 반환할 때 CORS 헤더는 전송되지 않습니다.그리고 CORS 문제가 있을 때는 답변을 읽을 수 없습니다.
DevTools에서 직접 확인할 수 있습니다.
당신이 원한다면 그들의 GitHub repo에서 문제를 제기할 수 있습니다.
언급URL : https://stackoverflow.com/questions/54990622/catch-error-message-from-404-response-with-axios-or-fetch-in-javascript
반응형
'IT이야기' 카테고리의 다른 글
Eclipse의 열린 리소스 대화 상자에서 .class 파일을 숨기려면 어떻게 해야 합니까? (0) | 2022.07.19 |
---|---|
구축과컴파일(Java) (0) | 2022.07.19 |
64비트 정수로 패킹된8비트 정수를 1씩 병렬로 빼서 하드웨어 SIMD를 사용하지 않음SWAR (0) | 2022.07.19 |
운영체제는 어떤 종류의 C로 기술되어 있습니까? (0) | 2022.07.19 |
Java Array 처음에 요소를 추가하는 방법 목록 (0) | 2022.07.12 |