zoukankan      html  css  js  c++  java
  • fetch的用法

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

    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)
                        }
                    }
                }
            })
        }
    }
  • 相关阅读:
    8种Nosql数据库系统对比
    How to get the value of a form element : check box and radio button
    Jquery 操作Html 控件 CheckBox、Radio、Select 控件
    Reading CheckBoxes and Radio Buttons
    java中的匿名内部类总结
    如何理解java泛型类
    java 多态
    linux下使用 du查看某个文件或目录占用磁盘空间的大小
    内网ip范围
    Nginx配置优化参考
  • 原文地址:https://www.cnblogs.com/lmxxlm-123/p/9297309.html
Copyright © 2011-2022 走看看