zoukankan      html  css  js  c++  java
  • 封装及调用fetch

    一、封装fetch

    创建fetch/index.js

    import 'whatwg-fetch'
    import 'es6-promise'
    
    export function get(url) {
        let result = fetch(url, {
            credentials: 'include',
            headers: {
                'Access-Control-Allow-Origin': '*',
                'Accept': 'application/json, text/plain, */*'
            },
            // 设置允许cors跨域
            mode: 'cors'
        });
        return result;
    }
    
    // 将对象拼接成 key1=val1&key2=val2&key3=val3 的字符串形式
    function obj2params(obj) {
        let result = '';
        let item;
        for (item in obj) {
            result += '&' + item + '=' + encodeURIComponent(obj[item]);
        }
        
        if (result) {
            result = result.slice(1);
        }
        
        return result;
    }
    
    // 发送 post 请求
    export function post(url, paramsObj) {
        let 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;
    }

    二、调用fetch

    1、使用then

    import {get} from '../fetch/index';
    get("./mock/list.json").then((res) => {
                return res.json();
            }).then((json)=>{
                this.setState({
                    dataList: json.data
                })
            }).catch(function (err) {
                console.log(err);
            })
    

      

    二、async、await

    import {get} from '../fetch/index';
    let login = async () => {
             try { 
               let json = await post("#", {
                 password: password,
                 username: username
               });
               let data = await json.json();
               console.log(data);
             } catch (err) {
               console.log(err)
             }
           }
           login()
    

      

  • 相关阅读:
    【R】如何去掉数据框中包含非数值的行?
    解读NoSQL数据库的四大家族
    MapReduce
    从网站上扒网页,保存为file文件格式
    jfinal 模板引擎
    pycharm的版本对应问题
    AttributeError: module 'DBBase' has no attribute 'DBBase'
    四则运算 python
    用命令行去运行程序
    Pandas入门CNV.TXT数据分析
  • 原文地址:https://www.cnblogs.com/detanx/p/fetchQ2.html
Copyright © 2011-2022 走看看