Fetch是什么?与ajax有什么区别?

Fetch API 提供了一个 JavaScript 接口,用于访问和操纵 HTTP 管道的一些具体部分,例如请求和响应。它还提供了一个全局 fetch() 方法,该方法提供了一种简单,合理的方式来跨网络异步获取资源。
这种功能以前是使用 XMLHttpRequest 实现的。Fetch 提供了一个更理想的替代方案,可以很容易地被其他技术使用,例如 Service Workers (en-US)。Fetch 还提供了专门的逻辑空间来定义其他与 HTTP 相关的概念,例如 CORS 和 HTTP 的扩展。
请注意,fetch 规范与 jQuery.ajax() 主要有三种方式的不同:
1.当接收到一个代表错误的 HTTP 状态码时,从 fetch() 返回的 Promise 不会被标记为 reject, 即使响应的 HTTP 状态码是 404 或 500。相反,它会将 Promise 状态标记为 resolve (但是会将 resolve 的返回值的 ok 属性设置为 false ),仅当网络故障时或请求被阻止时,才会标记为 reject。
2.fetch() 可以不会接受跨域 cookies;你也可以不能使用 fetch() 建立起跨域会话。
3.fetch 不会发送 cookies。除非你使用了credentials 的初始化选项。

fetch是一种HTTP数据请求的方式,是XMLHttpRequest的一种替代方案。fetch不是ajax的进一步封装,而是原生js。Fetch函数就是原生js,没有使用XMLHttpRequest对象。

ajax

使用步骤
1.创建XmlHttpRequest对象
2.调用open方法设置基本请求信息
3.设置发送的数据,发送请求
4.注册监听的回调函数
5.拿到返回值,对页面进行更新

示例代码如下:

//1.创建Ajax对象
    if(window.XMLHttpRequest){
    
    
       var oAjax=new XMLHttpRequest();
    }else{
    
    
       var oAjax=new ActiveXObject("Microsoft.XMLHTTP");
    }

    //2.连接服务器(打开和服务器的连接)
    oAjax.open('GET', url, true);

    //3.发送
    oAjax.send();

    //4.接收
    oAjax.onreadystatechange=function (){
    
    
       if(oAjax.readyState==4){
    
    
           if(oAjax.status==200){
    
    
              //alert('成功了:'+oAjax.responseText);
              fnSucc(oAjax.responseText);
           }else{
    
    
              //alert('失败了');
              if(fnFaild){
    
    
                  fnFaild();
              }
           }
        }
    };

fetch

特点
1、第一个参数是URL
2、第二个是可选参数,可以控制不同配置的 init 对象;
3、使用了 JavaScript Promises 来处理结果/回调
fetch() 接受第二个可选参数,一个可以控制不同配置的 init 对象;
一个基本的 fetch 请求设置起来很简单。看看下面的代码:

fetch('http://example.com/movies.json')
  .then(function(response) {
    
    
    return response.json();
  })
  .then(function(myJson) {
    
    
    console.log(myJson);
  });

这里我们通过网络获取一个 JSON 文件并将其打印到控制台。最简单的用法是只提供一个参数用来指明想 fetch() 到的资源路径,然后返回一个包含响应结果的promise(一个 Response 对象)。

当然它只是一个 HTTP 响应,而不是真的JSON。为了获取JSON的内容,我们需要使用 json() 方法(在 Body mixin 中定义,被 RequestResponse 对象实现)。
支持的请求参数

参考 fetch(),查看所有可选的配置和更多描述。

// Example POST method implementation:

postData('http://example.com/answer', {
    
    answer: 42})
  .then(data => console.log(data)) // JSON from `response.json()` call
  .catch(error => console.error(error))

function postData(url, data) {
    
    
  // Default options are marked with *
  return fetch(url, {
    
    
    body: JSON.stringify(data), // must match 'Content-Type' header
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, same-origin, *omit
    headers: {
    
    
      'user-agent': 'Mozilla/4.0 MDN Example',
      'content-type': 'application/json'
    },
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, cors, *same-origin
    redirect: 'follow', // manual, *follow, error
    referrer: 'no-referrer', // *client, no-referrer
  })
  .then(response => response.json()) // parses response to JSON
}

上传 JSON 数据

使用 fetch() POST JSON数据

var url = 'https://example.com/profile';
var data = {
    
    username: 'example'};

fetch(url, {
    
    
  method: 'POST', // or 'PUT'
  body: JSON.stringify(data), // data can be `string` or {object}!
  headers: new Headers({
    
    
    'Content-Type': 'application/json'
  })
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));

fetch的配置

Promise fetch(String url [, Object options]);
Promise fetch(Request req [, Object options]);

fetch封装

export default async(url = '', data = {
    
    }, type = 'GET', method = 'fetch') => {
    
    
    type = type.toUpperCase();
    url = baseUrl + url;

    if (type == 'GET') {
    
    
        let dataStr = ''; //数据拼接字符串
        Object.keys(data).forEach(key => {
    
    
            dataStr += key + '=' + data[key] + '&';
        })

        if (dataStr !== '') {
    
    
            dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
            url = url + '?' + dataStr;
        }
    }

    if (window.fetch && method == 'fetch') {
    
    
        let requestConfig = {
    
    
            credentials: 'include',//为了在当前域名内自动发送 cookie , 必须提供这个选项
            method: type,
            headers: {
    
    
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            mode: "cors",//请求的模式
            cache: "force-cache"
        }

        if (type == 'POST') {
    
    
            Object.defineProperty(requestConfig, 'body', {
    
    
                value: JSON.stringify(data)
            })
        }
        
        try {
    
    
            const response = await fetch(url, requestConfig);
            const responseJson = await response.json();
            return responseJson
        } catch (error) {
    
    
            throw new Error(error)
        }
    } else {
    
    
        return new Promise((resolve, reject) => {
    
    
            let requestObj;
            if (window.XMLHttpRequest) {
    
    
                requestObj = new XMLHttpRequest();
            } else {
    
    
                requestObj = new ActiveXObject;
            }

            let sendData = '';
            if (type == 'POST') {
    
    
                sendData = JSON.stringify(data);
            }

            requestObj.open(type, url, true);
            requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            requestObj.send(sendData);

            requestObj.onreadystatechange = () => {
    
    
                if (requestObj.readyState == 4) {
    
    
                    if (requestObj.status == 200) {
    
    
                        let obj = requestObj.response
                        if (typeof obj !== 'object') {
    
    
                            obj = JSON.parse(obj);
                        }
                        resolve(obj)
                    } else {
    
    
                        reject(requestObj)
                    }
                }
            }
        })
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42526440/article/details/115016741