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()
    

      

  • 相关阅读:
    HTML5: HTML5 Video(视频)
    HTML5: HTML5 Geolocation(地理定位)
    HTML5: HTML5 拖放
    HTML5: HTML5 MathML
    HTML5: HTML5 内联 SVG
    HTML5: HTML5 Canvas
    HTML5: HTML5 新元素
    HTML5: 浏览器支持
    HTML5: HTML5 介绍
    HTML5: 目录
  • 原文地址:https://www.cnblogs.com/detanx/p/fetchQ2.html
Copyright © 2011-2022 走看看