美文网首页
fetch 数据请求

fetch 数据请求

作者: yonglei_shang | 来源:发表于2017-10-25 16:53 被阅读142次

安装

使用 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 数据请求

    安装 使用 npm 安装 whatwg-fetch 和 es6-promisenpm install what...

  • Fetch数据请求

    fetch:是一种HTTP数据请求的方式,是XMLHttpRequest的一种替代方案。fetch:不是ajax的...

  • post 数据发送、接受(node 服务)

    背景:前端用 fetch发请求,在 node服务端获取post请求数据 方案:前后端均需配置 1、前端 fetch...

  • React Native--请求Web端(Java)网络数据

    1.在RN中使用fetch请求外部数据 //请求参数 letformData=newFormData(); for...

  • fetch记录一下子

    1.原生http请求 2.fetch请求 3.上面是封装多得fetch,直接使用的fetch fetch请求对某些...

  • React中的数据请求

    React中的数据请求 xhr jQuery中的$.ajax axios fetch fetch是ES6提供的一个...

  • ajax、axios、fetch

    fetch: 是一种HTTP数据请求的方式,是XMLHttpRequest的一种替代方案。fetch不是ajax的...

  • react 数据请求

    React请求远程数据首先下载: fetch/GET 定义posts 数组 componentDidMount ...

  • Fetch

    fetch是一种HTTP数据请求的方式,是XMLHttpRequest的一种替代方案。fetch不是ajax的进一...

  • ReactNative网络请求

    json字符串形式的fetch请求 form 形式的fetch请求

网友评论

      本文标题:fetch 数据请求

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