在上面的代码中需要注意两件事:
- fetch API返回一个promise对象,我们可以将其分配给变量并稍后执行 。
- 我们还必须调用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}在上面的代码中需要注意两件事:-- POST请求类似于GET请求 。我们还需要在fetch() API的第二个参数中发送method,body 和headers 属性 。
- 我们必须需要使用 JSON.stringify() 将对象转成字符串请求body参数
- 为GET 请求提供 axios.get(),为 POST 请求提供 axios.post()等提供不同的方法,这样使我们的代码更简洁 。
- 将响应代码(例如404、500)视为可以在catch()块中处理的错误,因此我们无需显式处理这些错误 。
- 它提供了与IE11等旧浏览器的向后兼容性
- 它将响应作为JSON对象返回,因此我们无需进行任何解析
// 在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
推荐阅读
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- 如何设置路由器的防蹭网功能?
- 不忘过去的人故事?不忘过去的人故事中老大的愿望是什么
- 汉灵帝如何使汉朝灭亡 汉灵帝有多少实权
- 安化松针加工工艺,如何挑选松针茶
- 芒景古树茶在哪里,云南景迈山古树茶
- 端口的作用
- 什么是端口?到底是做什么的呢?
- 藏在深山人渐识,路书香剑影
- 三国演义中对关羽形象的描写?《三国演义》中的关羽有什么特点
- 小威|人在职场,请一定要压得住脾气,沉得住气,才能做大事
