使用axios捕获来自404响应的错误消息或在javascript中获取

时间:2019-03-04 19:56:03

标签: javascript html vuejs2 cors axios

我正在尝试通过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消息(也许这是一个关键)

感谢您的帮助。 :)

1 个答案:

答案 0 :(得分:3)

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

您可以在DevTools中自行检查

enter image description here

enter image description here


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