React中的数据请求

2020-05-07  本文已影响0人  learninginto

React中的数据请求

fetch是ES6提供的一个数据请求方法,是属于浏览器自带的方法,存在一定的兼容性问题。

一般情况下会引入第三方封装的fetch : whatwg-fetch

cnpm install whatwg-fetch
  1. 返回promise
  2. 留给来开发者足够的操作空间
  3. fetch请求成功以后不会直接将数据返回给.then(),而是将一个未处理的结果集返回给用户。因此我们需要在第一个.then中解析数据,在第二个.then中获取数据
  4. 默认是不会携带cookie的需要配置credentials:"include"
import {fetch as fetchPro} from "whatwg-fetch"
get:
fetch(url,{
    headers:{}
}).then(()=>{}).then(()=>{})


import qs from "qs"//安装qs:cnpm i qs
post:
fetch(url,{
    methods:"post",
    headers:{
        "content-type":"application/x-www-form-urlencoded"
    }
    body:存放post提交的参数
}).then(()=>{}).then(()=>{})
import { fetch as fetchPro } from "whatwg-fetch";
import qs from "qs";

const get = (options) => {
    var str = "";
    var path = "";
    if (options.data) {
        for (var key in options.data) {
            str += `&${key}=${options.data[key]}`;
        }
    }
    path = options.url + "?" + str.slice(1);

    return fetchPro(path, {
        headers: {
            ...options.headers,
            "content-type": "application/json"
        },
        credentials: "include"
    }).then(res => res.json())
}


const post = (options) => {
    
    return fetchPro(options.url, {
        method: "post",
        headers: {
            ...options.headers,
            "content-type": "application/x-www-form-urlencoded"
        },
        credentials: "include",
        body: qs.stringify(options.data)
    }).then(res => res.json())
}

export default {
    get,
    post
}
上一篇 下一篇

猜你喜欢

热点阅读