美文网首页
fetch 使用

fetch 使用

作者: 赵碧菡 | 来源:发表于2017-11-15 20:24 被阅读0次

安装

npm install whatwg-fetch --save

为了兼容老版本浏览器,还需要安装

npm install es6-promise --save。

get 基本使用

引入依赖插件

import 'whatwg-fetch'
import 'es6-promise'

方法的第一个参数是 url 第二个参数是配置信息。

var result = fetch('/api/1', {
     credentials: 'include', 
     headers: { 'Accept': 'application/json, text/plain, */*' } 
});

以上代码的配置中,credentials: 'include'表示跨域请求是可以带cookie(fetch 跨域请求时默认不会带 cookie,需要时得手动指定 credentials: 'include'。headers可以设置 http 请求的头部信息。

fetch 方法请求数据,返回的是一个 Promise 对象

result.then(res => {
    return res.text()     // 将请求来的数据转化成 文本形式
 // return res.json()        // 将数据转换成json格式                
}).then(text => { 
  console.log(text)
 })

post 基本使用

fetch 发起一个 post 请求(有method: 'POST'),第一个参数是 url,第二个参数是配置信息。

var result = fetch('/api/post', { 
      method: 'POST', 
      credentials: 'include',
      headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/x-www-form-urlencoded' }, 
      body: "a=100&b=200"  // 注意 post 时候参数的形式 
});

fetch 提交数据之后,返回的结果也是一个 Promise 对象,跟 get 方法一样,处理方式也一样。

抽象 get 和 post

新建两个文件 post.js 和 get.js,分别对 get 方法 和 post 方法封装

//  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;
}
// 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;
}

这两个方法抽象之后,接下来我们新建一个data.js文件,在这个文件中引用

// data.js
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)
    })
}

.


参考文章 http://www.imooc.com/article/15003

相关文章

网友评论

      本文标题:fetch 使用

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