欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

fetch封装

程序员文章站 2022-05-02 20:30:15
...

1.直接上完整代码

import 'whatwg-fetch'
import 'es6-promise'
 
export function get(url) {
    let result = fetch(url, {
		method: 'POST',
        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;
}

2.使用
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);
})

相关标签: 封装