zoukankan      html  css  js  c++  java
  • React 之使用 fetch

    一.安装。

    1.根据文档提示,用 npm 安装的话,执行npm install whatwg-fetch --save即可安装。
    2.为了兼容老版本浏览器,还需要安装npm install es6-promise --save。安装完成之后,注意看一下package.json中的变化。

    二.基本使用.

    1.get 的基本使用

    import 'whatwg-fetch'
    import 'es6-promise'
    然后这样就可以发起一个 get 请求。这里的fetch是引用了插件之后即可用的方法,使用非常简单。方法的第一个参数是 url 第二个参数是配置信息。
        var result = fetch('/api/1', {
            credentials: 'include',
            headers: {
                'Accept': 'application/json, text/plain, */*'
            }
        });
    以上代码的配置中,credentials: 'include'表示跨域请求是可以带cookie(fetch 跨域请求时默认不会带 cookie,需要时得手动指定 credentials: 'include'
    这和 XHR 的 withCredentials 一样),headers可以设置 http 请求的头部信息。 fetch 方法请求数据,返回的是一个 Promise 对象,接下来我们就可以这样用了——完全使用Promise的语法结构。 result.then(res
    => { return res.text() }).then(text => { console.log(text) }) 或者这样用 result.then(res => { return res.json() }).then(json => { console.log(json) }) 注意,以上两个用法中,只有res.text()和res.json()这里不一样————这两个方法就是将返回的 Response 数据转换成字符串或者JSON格式,这也是 js 中常用的两种格式。

    2.post 的基本使用

    import 'whatwg-fetch'
    import 'es6-promise'
    然后用 fetch 发起一个 post 请求(有method: 'POST'),第一个参数是 url,第二个参数是配置信息。注意下面配置信息中的headers和body的格式。
        var result = fetch('/api/post', {
            method: 'POST',
            credentials: 'include',
            headers: {
                'Accept': 'application/json, text/plain, */*',
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            // 注意 post 时候参数的形式
            body: "a=100&b=200"
        });
    fetch 提交数据之后,返回的结果也是一个 Promise 对象,跟 get 方法一样,因此处理方式也一样,上面刚描述了,因此不再赘述。
    抽象get和post
    如果每次获取数据,都向上面一样写好多代码,就太冗余了,我们这里将 get 和 post 两个方法单独抽象出来。参见get.js和post.js的源码。
    需要注意的是,post.js中,将参数做了处理。因为上面的代码中提到,body: "a=100&b=200"这种参数格式是有要求的,而我们平时在 js 中使用最多的是 JSON 格式的数据,
    因此需要转换一下,让它更加易用。 这两个方法抽象之后,接下来我们再用,就变得相当简单了。参见 .
    /app/fetch/data.js // '/api/1' 获取字符串 var result = get('/api/1') result.then(res => { return res.text() }).then(text => { console.log(text) })

    3.get.js的抽象

    import 'whatwg-fetch'
    import 'es6-promise'
    
    export function get(url) {
      var result = fetch(url, {
          credentials: 'include',
          headers: {
              'Accept': 'application/json, text/plain, */*'
          }
      });
    
      return result;
    }

    4.post.js的抽象

    import 'whatwg-fetch'
    import 'es6-promise'
    
    // 将对象拼接成 key1=val1&key2=val2&key3=val3 的字符串形式
    function obj2params(obj) {
        var result = '';
        var item;
        for (item in obj) {
            result += '&' + item + '=' + encodeURIComponent(obj[item]);
        }
    
        if (result) {
            result = result.slice(1);
        }
    
        return result;
    }
    
    // 发送 post 请求
    export function post(url, paramsObj) {
        var result = fetch(url, {
            method: 'POST',
            credentials: 'include',
            headers: {
                'Accept': 'application/json, text/plain, */*',
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: obj2params(paramsObj)
        });
    
        return result;
    }

    5.实例应用

    import { get } from './get.js'
    import { post } from './post.js'
    
    export function getData() {
        // '/api/1' 获取字符串
        var result = get('/api/1')
    
        result.then(res => {
            return res.text()
        }).then(text => {
            console.log(text)
        })
    
        // '/api/2' 获取json
        var result1 = get('/api/2')
    
        result1.then(res => {
            return res.json()
        }).then(json => {
            console.log(json)
        })
    }
    
    export function postData() {
        // '/api/post' 提交数据
        var result = post('/api/post', {
            a: 100,
            b: 200
        })
    
        result.then(res => {
            return res.json()
        }).then(json => {
            console.log(json)
        })
    }

    6.官方提供POST Json数据的方法

    Post JSON
    
    fetch('/users', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        name: 'Hubot',
        login: 'hubot',
      })
    })

     原文链接:http://www.imooc.com/article/15003

  • 相关阅读:
    TensorFlow 使用预训练好的卷积神经网络和循环神经网络(lstm)模型处理图片转文字(im2txt)
    45度做人,90度做事,180度为人,360度处事
    SQL Server 和 Oracle 数据类型对应关系
    SQL Server 创建数据库
    SQL Server 2012 忘记sa用户处理方法
    剑指offer50:数组中重复的数字
    剑指offer49:把字符串转换成整数
    剑指offer48:不用加减乘除做加法
    剑指offer47:位运算+递归。求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
    剑指offer46:圆圈中最后剩下的数字(链表,递归)
  • 原文地址:https://www.cnblogs.com/wusheng2016/p/7572309.html
Copyright © 2011-2022 走看看