美文网首页javascript
Fetch请求后端数据的封装

Fetch请求后端数据的封装

作者: 变态的小水瓶 | 来源:发表于2018-12-07 14:46 被阅读51次

import { message } from 'antd';

function post(url,params,callback,headers){

        console.log('post-请求接口:'+ url);

        console.log('请求参数:'+JSON.stringify(params));

        if(!headers) {

                headers={

                        'Accept':'application/json',// 通过头指定,获取的数据类型是JSON

                        'Content-Type':'application/json',

                 }

         }

        let fetchOptions = {

                method:"POST",

                headers: headers,

                body:JSON.stringify(params)

        };

        fetch( url , fetchOptions ).then( (response)=>response.json() ).then((obj)=>{

                if(obj.code ==200){

                    callback(obj);

                }else{

                    message.error(obj.msg);

                }

        })

}

function get(url,callback,headers){

        console.log('get-请求接口:'+ url);

        if(!headers) {

                headers={

                        'Accept':'application/json',// 通过头指定,获取的数据类型是JSON

                        'Content-Type':'application/json',

                }

        }

        let fetchOptions = {

                method:"GET",

                headers: headers,

        };

        fetch(url,fetchOptions).then((response) =>response.json()).then((obj)=>{

                if(obj.code ==200){

                        callback(obj.data);

                }else{

                        message.error(obj.msg);

                }

        })

}

export default{

    get:get,

    post:post

};

相关文章

网友评论

    本文标题:Fetch请求后端数据的封装

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