美文网首页
fetch实现客户端和服务器端的通信

fetch实现客户端和服务器端的通信

作者: Mr无愧于心 | 来源:发表于2018-09-19 14:18 被阅读0次
    • fetch不是AJAX,它诞生的目的是为了代替 ajax,它是JS中内置的API:基于fetch可以实现客户端和服务器端的信息通信:
    1. fetch是ES2018规范中新增的API,所以浏览器的支持度不是特别好(可以基于BABEL的最新语法解析包,把其进行解析),想要兼容性好一些,需要使用 “fetch polyfill”
    2. 使用fetch发送请求
      => get/head等请求不能设置body
      => 不管服务器返回的状态是多少,fetch都不认为是失败(那怕是4或者5开头的状态码),都执行的是then中的方法(需要我们自己进行异常抛出处理)

    示例

    fetch('https://www.easy-mock.com/mock/5b0412beda8a195fb0978627/temp/info2', {
            method: 'GET',
            headers: {
                //=>设置请求头
                'content-type': 'x-www-form-urlencoded'
            },
            //=>不管同源还是跨域请求都带着COOKIE信息
            credentials: 'include'
        }).then(result => {
            let {status} = result;//获取状态码,自己判断成功与否
            if (/^(4|5)\d{2}$/.test(status)) {
                throw new Error('query data is error!');
                return;
            }
             /* headers:{} 包含响应头信息
             * redirected:false 是否重定向
             * status:状态码
             * statusText
             * type:'basic'/'cors'
             * url:请求的地址
             * __proto__:Response
             *   arrayBuffer()
             *   blob()
             *   json()
             *   text()
             *   ...
             *   基于这些方法可以快速的把从服务器获取的结果找到
             */
        })
    
    
    
    fetch('https://www.easy-mock.com/mock/5b0412beda8a195fb0978627/temp/add', {
            method: 'POST',
            body: 'a=1&b=2'//=>BODY中只支持字符串(GET请求还无法设置BODY)
        }).then(result => {
            let {status} = result;
            if (/^(4|5)\d{2}$/.test(status)) {
                throw new Error('query data is error!');
                return;
            }
            return result.json();
        })
    

    相关文章

      网友评论

          本文标题:fetch实现客户端和服务器端的通信

          本文链接:https://www.haomeiwen.com/subject/jvlinftx.html