【问题标题】:catch error message from 404 response with axios or fetch in javascript使用 axios 从 404 响应中捕获错误消息或在 javascript 中获取
【发布时间】:2019-07-26 04:49:40
【问题描述】:

我正在尝试使用 axios 支持来自 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 消息(也许这是一个键)

感谢您的帮助。 :)

【问题讨论】:

    标签: javascript html vuejs2 cors axios


    【解决方案1】:

    这是 The Rick and Morty API 的限制。当请求返回 404 时,它不会发送 CORS 标头。当出现 CORS 问题时,您无法读取响应。

    您可以在 DevTools 中自行检查


    如果需要,您可以在他们的GitHub repo 提出问题。

    【讨论】:

      猜你喜欢
      • 2019-01-18
      • 2020-07-15
      • 1970-01-01
      • 2016-03-25
      • 2018-05-15
      • 2016-03-12
      • 2018-12-20
      • 2020-09-10
      • 2018-01-16
      相关资源
      最近更新 更多