使用fetch

安装

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

get 的基本使用

  • 首先要引入依赖的插件

    1
    2
    import 'whatwg-fetch'
    import 'es6-promise'
  • 方法的第一个参数是 url, 第二个参数是配置信息

    1
    2
    3
    4
    5
    6
    var result = fetch('/api/1', {
    credentials: 'include',
    headers: {
    'Accept': 'application/json, text/plain, */*'
    }
    });
  • credentials: ‘include’表示跨域请求是可以带cookie(fetch 跨域请求时默认不会带 cookie,需要时得手动指定 credentials: ‘include’。

  • headers可以设置 http 请求的头部信息。
  • fetch 方法请求数据,返回的是一个 Promise 对象,接下来我们就可以这样用了——完全使用Promise的语法结构。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    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 中常用的两种格式。

post 的基本使用

  • 首先要引入依赖的插件

    1
    2
    import 'whatwg-fetch'
    import 'es6-promise'
  • 然后用 fetch 发起一个 post 请求(有method: ‘POST’),第一个参数是 url,第二个参数是配置信息。注意下面配置信息中的headers和body的格式。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    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 方法一样,因此处理方式也一样