1.8 Fetch的轻量级封装

自己做项目中的重点知识,不是教程,如果学习的话可以拿来参考。源代码[地址][12]
[12]: https://github.com/BaiPeiHe/react-native

封装

// HttpUtils.js 文件
export default class HttpUtils{

    static get(url){
        return new Promise((resolve, reject)=>{
            fetch(url)
                .then(response=>response.json())
                .then(result=>{
                    resolve(result);
                })
                .catch(error=>{
                    reject(error);
                })
        })
    }

    static post(url,data){
        return new Promise((resolve,reject)=>{
            fetch(url,{
                method:'POST',
                header:{
                    'Accept':'application/json',
                    'Content-Tyoe':'application/json'
                },
                body:JSON.stringify(data)
            })
                .then(response=>response.json())
                .then(result=>{
                    resolve(result);
                })
                .catch(error=>{
                    reject(error);
                })
        })
    }

}

调用

// GET
HttpUtils.get(url)
            .then(result=>{
                this.setState({
                    result:JSON.stringify(result)
                })
            })
            .catch(error=>{
                this.setState({
                    result:'err+' + JSON.stringify(error)
                })
            })
// POST
HttpUtils.post(url,data)
            .then(result=>{
                this.setState({
                    result:JSON.stringify(result)
                })
            })
            .catch(error=>{
                this.setState({
                    result:'err + ' + JSON.stringify(error)
                })
            })

你可能感兴趣的:(1.8 Fetch的轻量级封装)