fetch的用法

1、重构公司的后台项目,偶然间在git上看见别人的项目中用到fetch,查了下才知道是ES6的新特性,和ajax的功能相似,都是实现请求,但是多少有些兼容性问题。

(1)fetch和XMLHttpRequest
fetch就是XMLHttpRequest的一种替代方案,除了XMLHttpRequest对象来获取后台的数据之外,还可以使用一种更优的解决方案fetch。

(2)如何获取fetch
https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API
使用第三方的ployfill来实现只会fetch
https://github.com/github/fetch

(3)fetch的helloworld
// 通过fetch获取百度的错误提示页面
fetch(‘https://www.baidu.com/search/error.html‘) // 返回一个Promise对象
  .then((res)=>{
    return res.text() // res.text()是一个Promise对象
  })
  .then((res)=>{
    console.log(res) // res是最终的结果
  })

(4)GET请求
// 通过fetch获取百度的错误提示页面
fetch(‘https://www.baidu.com/search/error.html‘, {
    method: ‘GET‘
  })
  .then((res)=>{
    return res.text()
  })
  .then((res)=>{
    console.log(res)
  })

GET请求的参数传递
GET请求中如果需要传递参数怎么办?这个时候,只能把参数写在URL上来进行传递了。
// 通过fetch获取百度的错误提示页面
fetch(‘https://www.baidu.com/search/error.html?a=1&b=2‘, { // 在URL中写上传递的参数
    method: ‘GET‘
  })
  .then((res)=>{
    return res.text()
  })
  .then((res)=>{
    console.log(res)
  })

(5)POST请求
// 通过fetch获取百度的错误提示页面
fetch(‘https://www.baidu.com/search/error.html‘, {
    method: ‘POST‘ // 指定是POST请求
  })
  .then((res)=>{
    return res.text()
  })
  .then((res)=>{
    console.log(res)
  })

POST请求参数的传递
众所周知,POST请求的参数,一定不能放在URL中,这样做的目的是防止信息泄露

// 通过fetch获取百度的错误提示页面
fetch(‘https://www.baidu.com/search/error.html‘, {
    method: ‘POST‘,
    body: new URLSearchParams([["foo", 1],["bar", 2]]).toString() // 这里是请求对象
  })
  .then((res)=>{
    return res.text()
  })
  .then((res)=>{
    console.log(res)
  })

(6)设置请求的头信息
一般是表单提交,现默认的提交方式是:Content-Type:text/plain;charset=UTF-8,不合理,下面指定请求方式
// 通过fetch获取百度的错误提示页面
fetch(‘https://www.baidu.com/search/error.html‘, {
    method: ‘POST‘,
    headers: new Headers({
      ‘Content-Type‘: ‘application/x-www-form-urlencoded‘ // 指定提交方式为表单提交
    }),
    body: new URLSearchParams([["foo", 1],["bar", 2]]).toString()
  })
  .then((res)=>{
    return res.text()
  })
  .then((res)=>{
    console.log(res)
  })

(7)通过接口得到JSON数据
返回的类型:https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch#Body

// 通过fetch获取百度的错误提示页面
fetch(‘https://www.baidu.com/rec?platform=wise&ms=1&rset=rcmd&word=123&qid=11327900426705455986&rq=123&from=844b&baiduid=A1D0B88941B30028C375C79CE5AC2E5E%3AFG%3D1&tn=&clientWidth=375&t=1506826017369&r=8255‘, { // 在URL中写上传递的参数
    method: ‘GET‘,
    headers: new Headers({
      ‘Accept‘: ‘application/json‘ // 通过头指定,获取的数据类型是JSON
    })
  })
  .then((res)=>{
    return res.json() // 返回一个Promise,可以解析成JSON
  })
  .then((res)=>{
    console.log(res) // 获取JSON数据
  })

(8)强制带Cookie
默认情况下, fetch 不会从服务端发送或接收任何 cookies, 如果站点依赖于维护一个用户会话,则导致未经认证的请求(要发送 cookies,必须发送凭据头).

// 通过fetch获取百度的错误提示页面
fetch(‘https://www.baidu.com/search/error.html‘, {
    method: ‘GET‘,
    credentials: ‘include‘ // 强制加入凭据头
  })
  .then((res)=>{
    return res.text()
  })
  .then((res)=>{
    console.log(res)
  })

(9)简单封装一下fetch
/**
 * 将对象转成 a=1&b=2的形式
 * @param obj 对象
 */
function obj2String(obj, arr = [], idx = 0) {
  for (let item in obj) {
    arr[idx++] = [item, obj[item]]
  }
  return new URLSearchParams(arr).toString()
}

/**
 * 真正的请求
 * @param url 请求地址
 * @param options 请求参数
 * @param method 请求方式
 */
function commonFetcdh(url, options, method = ‘GET‘) {
  const searchStr = obj2String(options)
  let initObj = {}
  if (method === ‘GET‘) { // 如果是GET请求,拼接url
    url += ‘?‘ + searchStr
    initObj = {
      method: method,
      credentials: ‘include‘
    }
  } else {
    initObj = {
      method: method,
      credentials: ‘include‘,
      headers: new Headers({
        ‘Accept‘: ‘application/json‘,
        ‘Content-Type‘: ‘application/x-www-form-urlencoded‘
      }),
      body: searchStr
    }
  }
  fetch(url, initObj).then((res) => {
    return res.json()
  }).then((res) => {
    return res
  })
}

/**
 * GET请求
 * @param url 请求地址
 * @param options 请求参数
 */
function GET(url, options) {
  return commonFetcdh(url, options, ‘GET‘)
}

/**
 * POST请求
 * @param url 请求地址
 * @param options 请求参数
 */
function POST(url, options) {
  return commonFetcdh(url, options, ‘POST‘)
}

2、下面是封装好的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‘,
            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)
                    }
                }
            }
        })
    }
}

3、借鉴:https://segmentfault.com/a/1190000011433064

原文地址:https://www.cnblogs.com/lmxxlm-123/p/9297309.html

时间: 2024-08-30 01:26:54

fetch的用法的相关文章

ajax与fetch的用法

// 传统ajax用法 var xhr = new XMLHttpRequest(); xhr.responseType = 'json'; xhr.timeout = 2000; console.log(xhr.readyState);//0 xhr.open('GET', url); console.log(xhr.readyState);//1 xhr.onloadstart = function (e) { xhr.abort(); console.log(e); }; xhr.onpr

[转] 学会fetch的用法

fetch是web提供的一个可以获取异步资源的api,目前还没有被所有浏览器支持,它提供的api返回的是Promise对象,所以你在了解这个api前首先得了解Promise的用法.参考阮老师的文章 那我们首先讲讲在没有fetch的时候,我们是如何获取异步资源的: //发送一个get请求是这样的: //首先实例化一个XMLHttpRequest对象 var httpRequest = new XMLHttpRequest(); //注册httpRequest.readyState改变时会回调的函数

git clone, push, pull, fetch 的用法

Git是目前最流行的版本管理系统,学会Git几乎成了开发者的必备技能. Git有很多优势,其中之一就是远程操作非常简便.本文详细介绍5个Git命令,它们的概念和用法,理解了这些内容,你就会完全掌握Git远程操作. git clone git remote git fetch git pull git push 本文针对初级用户,从最简单的讲起,但是需要读者对Git的基本用法有所了解.同时,本文覆盖了上面5个命令的几乎所有的常用用法,所以对于熟练用户也有参考价值. git 一.git clone

fetch()的用法

发起获取资源请求的我们一般都会用AJAX技术,最近在学习微信小程序的时候,用到了fetch()方法. fetch()方法用于发起获取资源的请求.它返回一个promise,这个promise会在请求响应之后被resolve,并传回Response对象,基本上在任何场景下只要你想获取资源,都可以使用fetch()方法,但是现在存在兼容性的问题,查看兼容性:http://caniuse.com/#search=fetch() 当遇到网络错误是,fetch()返回的promise会被reject(阻止)

Hibernate fetch 抓取策略

上一篇文章(Hibernate的延迟加载 ,懒加载,lazy)说到Hibernate的延迟加载跟fetch的配置还有一定关系,下面就来讨论下fetch的用法. 抓取策略(fetch)是指当我们去查询一个对象里面所关联的其他对象时,按照哪种方法去抓取关联对象. fetch策略一共有四种:select.subselect.join.batch,下面我们一一介绍.我们还是用上面介绍延迟加载的相关表和实体类. Company表: Employee表(employee_company_id为外键) Com

git fetch和push的区别

获取fetch的用法 git-fetch用于从另一个reposoitory下载objects和refs. 命令格式为:git fetch … 其中表示远端的仓库路径.git remote add origin [email protected]:schacon/simplegit-progit.git 其中的标准格式应该为:,表示远端仓库的分支,如果不为空,则表示本地的分支:如果为空,则使用当前分支. git fetch /home/bob/myrepo master:bobworks :用于从

fetch和XMLHttpRequest讲解

写在前面 fetch 同 XMLHttpRequest 非常类似,都是用来做网络请求.但是同复杂的XMLHttpRequest的API相比,fetch使用了Promise,这让它使用起来更加简洁,从而避免陷入"回调地狱". 两者比较 比如,如果我们想要实现这样一个需求:请求一个URL地址,获取响应数据并将数据转换成JSON格式.使用fetch和XMLHttpRequest实现的方式是不同的. 使用XMLHttpRequest实现 使用XMLHttpRequest来实现改功能需要设置两个

PHP PDO操作MYSQL

PHP PDO操作MYSQL 学习要点: 1.        PHP PDO配置 2.        连接mysql及异常处理 3.        query,exec用法详解 4.        预处理prepare()用法详解 5.        PDO错误处理模式和事务处理 6.        获取和遍历结果集 7.        常用函数说明   我的博客:http://www.unitbuy.com PDO配置 PHP 数据对象 (PDO) 扩展可以支持绝大多数的主流的数据库,如下 C

Python爬虫框架Scrapy 学习笔记 6 ------- 基本命令

1. 有些scrapy命令,只有在scrapy project根目录下才available,比如crawl命令 2 . scrapy genspider taobao http://detail.tmall.com/item.htm?id=12577759834 自动在spider目录下生成taobao.py # -*- coding: utf-8 -*- import scrapy class TaobaoSpider(scrapy.Spider):     name = "taobao&qu