在 JS 中如何使用 Ajax 来进行请求( 二 )

在上面的代码中需要注意两件事:

  1. fetch API返回一个promise对象,我们可以将其分配给变量并稍后执行 。
  2. 我们还必须调用response.json()将响应对象转换为JSON
错误处理
我们来看看当HTTP GET请求抛出500错误时会发生什么:
fetch('http://httpstat.us/500') // this API throw 500 error  .then(response => () => {    console.log("Inside first then block");    return response.json();  })  .then(json => console.log("Inside second then block", json))  .catch(err => console.error("Inside catch block:", err));Inside first then block? ? Inside catch block: SyntaxError: Unexpected token I in JSON at position 4我们看到,即使API抛出500错误,它仍然会首先进入then()块,在该块中它无法解析错误JSON并抛出catch()块捕获的错误 。
这意味着如果我们使用fetch()API,则需要像这样显式地处理此类错误:-
fetch('http://httpstat.us/500')  .then(handleErrors)  .then(response => response.json())  .then(response => console.log(response))  .catch(err => console.error("Inside catch block:", err));function handleErrors(response) {  if (!response.ok) { // throw error based on custom conditions on response      throw Error(response.statusText);  }  return response;} ? Inside catch block: Error: Internal Server Error at handleErrors (Script snippet %239:9)3.3 示例:POSTfetch('https://jsonplaceholder.typicode.com/todos', {    method: 'POST',    body: JSON.stringify({      completed: true,      title: 'new todo item',      userId: 1    }),    headers: {      "Content-type": "application/json; charset=UTF-8"    }  })  .then(response => response.json())  .then(json => console.log(json))  .catch(err => console.log(err))Response? {completed: true, title: "new todo item", userId: 1, id: 201}在上面的代码中需要注意两件事:-
  1. POST请求类似于GET请求 。我们还需要在fetch() API的第二个参数中发送method,body 和headers 属性 。
  2. 我们必须需要使用 JSON.stringify() 将对象转成字符串请求body参数
4.AxIOS APIAxios API非常类似于fetch API,只是做了一些改进 。我个人更喜欢使用Axios API而不是fetch() API,原因如下:
  • 为GET 请求提供 axios.get(),为 POST 请求提供 axios.post()等提供不同的方法,这样使我们的代码更简洁 。
  • 将响应代码(例如404、500)视为可以在catch()块中处理的错误,因此我们无需显式处理这些错误 。
  • 它提供了与IE11等旧浏览器的向后兼容性
  • 它将响应作为JSON对象返回,因此我们无需进行任何解析
4.1 示例:GET// 在chrome控制台中引入脚本的方法var script = document.createElement('script');script.type = 'text/javascript';script.src = 'https://unpkg.com/axios/dist/axios.min.js';document.head.appendChild(script);axios.get('https://jsonplaceholder.typicode.com/todos/1')  .then(response => console.log(response.data))  .catch(err => console.error(err));Response{ userId: 1, id: 1, title: "delectus aut autem", completed: false }我们可以看到,我们直接使用response获得响应数据 。数据没有任何解析对象,不像fetch() API 。
错误处理
axios.get('http://httpstat.us/500')  .then(response => console.log(response.data))  .catch(err => console.error("Inside catch block:", err));Inside catch block: Error: Network Error


推荐阅读