美文网首页
React Native 之fetch常用请求封装

React Native 之fetch常用请求封装

作者: JMCC117 | 来源:发表于2017-05-05 18:05 被阅读0次

    封装的文件为http.js,import的storage是asyncStorage的setitem,getitem的封装。

    let queryString = require('query-string');
    import Storage from './storage'
    import {
        Platform
    } from 'react-native'
    
    const os = Platform.OS;
    
    function checkStatus(response) {
        if (response.status >= 200 && response.status < 300) {
            return response
        } else {
            let error = new Error(response.statusText)
            error.response = response
            throw error
        }
    }
    function parseJSON(response) {
        return response.json()
    }
    async function get(url, params) {
        if (params) {
            url += `?${queryString.stringify(params)}`
        }
        try {
            let headers = new Headers();
            let Access_Token = await Storage.getItem('Access_Token');
            if (Access_Token) {
                headers.append('Access_Token', Access_Token);
                headers.append('UserAgent',os);
            }
            console.log(headers,url)
            return fetch(url, {
                headers: headers
            })
                .then(checkStatus)
                .then(parseJSON)
        } catch (e) {
            throw new Error('get error')
        }
    
    }
    
    async function post(url, body) {
        let Access_Token = await Storage.getItem('Access_Token');
        let fetchOptions = {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'Access_Token': Access_Token ? Access_Token : '',
                'UserAgent':os
            },
            body: JSON.stringify(body)
        }
        return fetch(url, fetchOptions)
            .then(checkStatus)
            .then(parseJSON)
    }
    
    async function del(url, params) {
        if (params) {
            url += `?${queryString.stringify(params)}`
        }
        let Access_Token = await Storage.getItem('Access_Token');
        let fetchOptions = {
            method: 'DELETE',
            headers:{
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'Access_Token': Access_Token ? Access_Token : '',
                'UserAgent':os
            }
        }
        return fetch(url, fetchOptions)
            .then(checkStatus)
            .then(parseJSON)
    }
    
    async function update(url, body) {
        let Access_Token = await Storage.getItem('Access_Token');
        let fetchOptions = {
            method: 'PUT',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'Access_Token': Access_Token ? Access_Token : '',
                'UserAgent':os
            },
            body: JSON.stringify(body)
        }
        return fetch(url, fetchOptions)
            .then(checkStatus)
            .then(parseJSON)
    }
    
    async function uploadFile(url, params, fileUrl,fileName) {
        let Access_Token = await Storage.getItem('Access_Token');
        let data = new FormData();
        data.append('file', {
            uri: fileUrl,
            name: fileName,
            type: 'image/jpeg'
        });
    
        Object.keys(params).forEach((key)=> {
            if (params[key] instanceof Date) {
                data.append(key, value.toISOString())
            } else {
                data.append(key, String(params[key]))
            }
        });
        const fetchOptions = {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Access_Token': Access_Token ? Access_Token : '',
                'UserAgent':os
            },
            body: data
        };
        return fetch(url, fetchOptions)
            .then(checkStatus)
            .then(parseJSON)
    }
    export default {
        get,
        post,
        del,
        update,
        uploadFile
    }
    

    在需要用到的地方引入http文件,接收两个参数,第一个是地址,第二个是请求参数。


    使用方法

    相关文章

      网友评论

          本文标题:React Native 之fetch常用请求封装

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