fetch 数据请求

安装

使用 npm 安装 whatwg-fetches6-promise
npm install whatwg-fetch --save
npm install es6-promise --save

示例

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

//get请求
export function getDate() {
    var result = fetch('/api/1',{
        methods: 'GET',
        credentials: 'include',
        headers: {
            'Accept': 'application/json, text/plain, */*'
        }
    })

    result.then((res) => {
        return res.text()
    }).then((text) => {
        console.log(text) // 打印出来的为一个text数据
    })

    var result2 = fetch('/api/2',{
        methods: 'GET',
        credentials: 'include',
        headers: {
            'Accept': 'application/json, text/plain, */*'
        }
    })

    result.then((res) => {
        return res.json()
    }).then((json) => {
        console.log(json)// 打印出来的为一个json格式的数据
    })
}

//post 请求

//对象转换成字符串形式  item=1&item2=2
function paramesObj(obj) {
    var str = '',item;
    for (item in obj) {
        str += '&' + item + '=' + encodeURIComponent(obj[item])
    }

    if (str) {
        str = str.slice(1)
    }

    return str
}

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

    result.then((res) => {
        return res.json()
    }).then((json) => {
        console.log(json)
    })
}

你可能感兴趣的:(fetch 数据请求)