JavaScript中使用fetch进行异步请求

原创文章 作者:月光光 2017年07月22日 08:56helloweba.com 标签:Ajax 

在 AJAX 时代,进行 API 等网络请求都是通过 XMLHttpRequest 或者封装后的框架进行网络请求。 现在产生的 fetch 框架简直就是为了提供更加强大、高效的网络请求而生,虽然在目前会有一点浏览器兼容的问题,但是当我们进行一些异步请求时,都可以使用 fetch 进行完美的网络请求。

Ajax请求

普通的Ajax请求,用XHR发送一个json请求一般是这样的:

var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.responseType = 'json';
xhr.onload = function(){
    console.log(xhr.response);
};
xhr.onerror = function(){
    console.log("error")
}
xhr.send();

使用fetch实现的方式:

fetch(url).then(function(response){
    return response.json();
}).then(function(data){
    console.log(data)
}).catch(function(e){
    console.log("error")
})    

也可以用async/await的方式

try{
    let response = await fetch(url);
    let data = await response.json();
    console.log(data);
} catch(e){
    console.log("error")
}

用了await后,写异步代码感觉像同步代码一样爽。await后面可以跟Promise对象,表示等待Promise resolve()才会继续下去执行,如果Promise被reject()或抛出异常则会被外面的try...catch捕获。

使用fetch

fetch的主要优点是

  • 语法简洁,更加语义化
  • 基于标准的Promise实现,支持async/await
  • 同构方便

但是也有它的不足

  • fetch请求默认是不带cookie的,需要设置fetch(url, {credentials: 'include'})
  • 服务器返回400,500这样的错误码时不会reject,只有网络错误这些导致请求不能完成时,fetch才会被reject.

fetch语法:

fetch(url, options).then(function(response) {
  // handle HTTP response
}, function(error) {
  // handle network error
})

具体参数案例:

//兼容包
require('babel-polyfill')
require('es6-promise').polyfill()

import 'whatwg-fetch'

fetch(url, {
  method: "POST",
  body: JSON.stringify(data),
  headers: {
    "Content-Type": "application/json"
  },
  credentials: "same-origin"
}).then(function(response) {
  response.status     //=> number 100–599
  response.statusText //=> String
  response.headers    //=> Headers
  response.url        //=> String

  response.text().then(function(responseText) { ... })
}, function(error) {
  error.message //=> String
})

参数说明

url

定义要获取的资源。这可能是:一个 USVString 字符串,包含要获取资源的 URL。一个 Request 对象。

options(可选)

一个配置项对象,包括所有对请求的设置。可选的参数有:

method: 请求使用的方法,如 GET、POST。

headers: 请求的头信息,形式为 Headers 对象或 ByteString。

body: 请求的 body 信息:可能是一个 Blob、BufferSource、FormData、URLSearchParams 或者 USVString 对象。注意 GET 或 HEAD 方法的请求不能包含 body 信息。

mode: 请求的模式,如 cors、 no-cors 或者 same-origin。

credentials: 请求的 credentials,如 omit、same-origin 或者 include。

cache: 请求的 cache 模式: default, no-store, reload, no-cache, force-cache, 或者 only-if-cached。

response

一个 Promise,resolve 时回传 Response 对象:

属性:

status (number) - HTTP请求结果参数,在100–599 范围

statusText (String) - 服务器返回的状态报告

ok (boolean) - 如果返回200表示请求成功则为true

headers (Headers) - 返回头部信息,下面详细介绍

url (String) - 请求的地址

方法:

text() - 以string的形式生成请求text

json() - 生成JSON.parse(responseText)的结果

blob() - 生成一个Blob

arrayBuffer() - 生成一个ArrayBuffer

formData() - 生成格式化的数据,可用于其他的请求

其他方法:

clone()

Response.error()

Response.redirect()

response.headers

has(name) (boolean) - 判断是否存在该信息头

get(name) (String) - 获取信息头的数据

getAll(name) (Array) - 获取所有头部数据

set(name, value) - 设置信息头的参数

append(name, value) - 添加header的内容

delete(name) - 删除header的信息

forEach(function(value, name){ ... }, [thisContext]) - 循环读取header的信息

使用实例

//获取css里ul的id属性
let uldom = document.getElementById("students");
//单独创建一个json文件,获取地址
let url = "data.json";

function main(){
    fetch(url).then(respone=>{
        return respone.json();
    }).then(students=>{

        let html = ``;
        for(let i=0, l=students.length; i<l; i++){
            let name = students[i].name;
            let age = students[i].age;
            html += `
                <li>姓名:${name},年龄:${age}</li>
                `
        }

        uldom.innerHTML = html;
    });
}

main();

结合await最终代码

let uldom = document.getElementById("students");
let url = "data.json";

async function main(){
    let respone = await fetch(url);
    let students = await respone.json();

let html =``;
for(let i=0, l=students.length; i<l; i++){
    let name = students[i].name;
    let age = students[i].age;
    html += `
    <li>姓名:${name},年龄:${age}</li>
`
}
uldom.innerHTML = html;
}
main();

data.json文件内容如下:

[
    {"name":"张三","age":"3"},
    {"name":"李万","age":"1"},
    {"name":"王二","age":"4"},
    {"name":"二狗","age":"3"},
    {"name":"狗蛋","age":"5"},
    {"name":"牛娃","age":"7"}
]

运行后结果是:

姓名:张三,年龄:3
姓名:李万,年龄:1
姓名:王二,年龄:4
姓名:二狗,年龄:3
姓名:狗蛋,年龄:5
姓名:牛娃,年龄:7
声明:本文为原创文章,helloweba.net和作者拥有版权,如需转载,请注明来源于helloweba.net并保留原文链接:https://www.helloweba.net/javascript/431.html

0条评论