簡體   English   中英

使用axios捕獲來自404響應的錯誤消息或在javascript中獲取

[英]catch error message from 404 response with axios or fetch in javascript

我正在嘗試使用axios支持來自api( https://rickandmortyapi.com )的404響應。

因此,當item存在時,響應如下所示:

{
  "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消息(也許這是一個關鍵)

感謝幫助。 :)

這是The Rick and Morty API的局限性。 當請求返回404時,它不會發送CORS標頭。並且,如果存在CORS問題,您將無法讀取響應。

您可以在DevTools中自行檢查

在此處輸入圖片說明

在此處輸入圖片說明


您可以根據需要在其GitHub存儲庫中提交問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM