Fetch基本网络请求

1、fetch概念

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline,
such as requests and responses.
It also provides a global fetch() method that provides an easy,
logical way to fetch resources asynchronously across the network.

Fetch API 提供了一个 JavaScript接口,用于访问和操纵HTTP管道的部分,例如请求和响应。
它还提供了一个全局 fetch()方法,该方法提供了一种简单,合乎逻辑的方式来跨网络异步获取资源。

2、fetch的使用

fetch常用的接口为fetch(url, config), 其中url为请求的地址,config为请求的配置对象包括配置请求方法,请求头等或者fetch(request),其中
request为Request对象,可以通过new方法构造。
fetch官网使用示例:

var myHeaders = new Headers();

var myInit = { method: 'GET',
               headers: myHeaders,
               mode: 'cors',
               cache: 'default' };

var myRequest = new Request('flowers.jpg', myInit);

fetch(myRequest).then(function(response) {
  return response.blob();
}).then(function(myBlob) {
  var objectURL = URL.createObjectURL(myBlob);
  myImage.src = objectURL;
});

实际使用示例:

static request() {
    let LoginUrl = 'http:xxx';
    let MD5 = require("crypto-js/md5");     // JavaScript环境提供的加密库,其中有很多加密算法
    let date = new Date();
    let currentTime = date.getTime();

    let requestObj = {
        a:'a', 
        b:'b',
        c:'c'
    }

    var fullDataParamsJSONString = JSON.stringify(requestObj);
    var checkSumKey = 'xxx';
    // 请求参数 时间 自定义key共同构成待加签字符串
    var checksum = fullDataParamsJSONString + currentTime + checkSumKey;
    // 对请求参数加签,用于服务器校验
    checksum = MD5(checksum).toString();

    // 请求的参数结构
    var fullRequestParameters = {
        currentTime: currentTime,
        data: fullDataParamsJSONString,
        checksum: checksum
    };

    // 请求配置
    let requestConfig = {
        method: 'POST', 
        headers: {
            Accept: 'application/json', 
            'Content-Type': 'application/json;charset=UTF-8'
        }, 
        // 请求体,将请求参数转化为json字符串
        body: JSON.stringify(fullRequestParameters), 
    };
    return fetch(LoginUrl, requestConfig);
}

3、fetch网络请求结果处理

fetch网络请求返回的是一个Promise对象并且传递了Response对象,所以可以在then或者catch方法中处理请求结果。
可以使用如下结构处理网络请求结果,其中reponse是Response对象,有多种方法转化为所需要的数据对象。具体可以参考Response对象文档。

fetch(url).then(response => {
    return response.json();
}).then(responseData => {
    // 正常请求处理
}).catch(err => {
    // 错误处理
}); 

4、fetch的超时处理

在fetch网络请求时,可以结合setTimeout和Promise来设置网络请求的超时处理。具体处理如下

static timeOutFetch() {
    let timeOutPromise = new Promise((resolve, reject) => {
        setTimeout(() => {
            reject('网络请求超时了....');
        }, 30000);
    });

    // 传入race中的promise需要中括号
    // race也会返回一个promise对象,其结果为两个promise中先完成的一个。
    return Promise.race([网络请求的promise, timeOutPromise]);
}

5、参考

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
https://developer.mozilla.org/en-US/docs/Web/API/Response

猜你喜欢

转载自blog.csdn.net/honeysx/article/details/78876352