美文网首页
React中的数据请求

React中的数据请求

作者: learninginto | 来源:发表于2020-05-07 23:46 被阅读0次

React中的数据请求

  • xhr
  • jQuery中的$.ajax
  • axios
  • fetch

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
}

相关文章

网友评论

      本文标题:React中的数据请求

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