ReactNative fetch網(wǎng)絡請求封裝(GET,POST,圖片上傳)

1、前言

最近學習RN進行到了網(wǎng)絡請求這一塊,便花了點時間把網(wǎng)絡請求封裝了一下,這樣使用起來也方便

2、結(jié)構(gòu)

  • Connect.js 對NetUtils的二次封裝,將地址添加進來,統(tǒng)一管理網(wǎng)絡請求
  • NetAddr.js 請求地址的存放
  • NetUtils.js get, post,圖片上傳的封裝
    image.png

3、代碼

  • NetUtils.js代碼里都有注釋
export default class NetUtils{
    /**
     *  GET 請求
     */
    static get(url, params, success, fail, error){
        if (params) {
            let paramsArray = [];
            //拼接參數(shù)
            Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
            if (url.search(/\?/) === -1) {
                url += '?' + paramsArray.join('&')
            } else {
                url += '&' + paramsArray.join('&')
            }
        }
        console.log(url, params)
        // fetch 請求
        fetch(url,{
            headers:{
              //看后臺需求決定配置參數(shù),例如我們后臺要求將appId放在這里請求
             // appId: '1234345656'
            },
        })
            .then(response=>response.json())//把response轉(zhuǎn)為json
            .then(responseJson=> { // 拿到上面的轉(zhuǎn)好的json
                console.log(responseJson) // 打印返回結(jié)果
                if (responseJson.code == 200){ // 200為請求成功
                   success && success(responseJson.data)
                }else {
                    fail && fail(responseJson.msg)//可以處理返回的錯誤信息
                }
            })
            .catch(e=>{
                console.log(e)
                error && error(e)
            })
    }

    /**
     *  POST 請求,經(jīng)測試用FormData傳遞數(shù)據(jù)也可以
     */
    static post(url, params, success, fail, error){
        console.log(url,params)
        fetch(url,{
            method: 'POST',
            headers:{
                'Accept': 'application/json',
                //媒體格式類型key/value格式
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: JSON.stringify(params)
        }) .then(response=>response.json())//把response轉(zhuǎn)為json
            .then(responseJson=> { // 拿到上面的轉(zhuǎn)好的json
                console.log(responseJson) // 打印返回結(jié)果
                if (responseJson.code == 200){ // 200為請求成功
                    success && success(responseJson.data)
                }else {
                    fail && fail(responseJson.msg)//可以處理返回的錯誤信息
                }
            })
            .catch(e=>{
                console.log(e)
                error && error(error)
            })
    }
    /**
     *  @images uri數(shù)組
     *  @param  FormData格式,沒有參數(shù)的話傳null
     */
    static uploadFile(url,images, params, success, fail, error){
        console.log(url,images)
        let formData = new FormData();
        if (params){
            formData = params;
        }
        for(var i = 0;i<images.length;i++){
            var uri = images[I]
            var date = new Date()
            var name = date.getTime() + '.png'//用時間戳保證名字的唯一性
            let file = {uri: uri, type: 'multipart/form-data', name: name}
            formData.append('file', file)
        }
        console.log(url,formData)
        fetch(url,{
            method: 'POST',
            headers:{
                'Accept': 'application/json',
                //媒體格式類型key/value格式
                'Content-Type':'multipart/form-data',
                customerId: customerId,
                appId: appId
            },
            body: formData
        }) .then(response=>response.json())//把response轉(zhuǎn)為json
            .then(responseJson=> { // 拿到上面的轉(zhuǎn)好的json
                console.log(responseJson) // 打印返回結(jié)果
                if (responseJson.code == 200){ // 200為請求成功
                    success && success(responseJson.data)
                }else {
                    fail && fail()//可以處理返回的錯誤信息
                }
            })
            .catch(e=>{
                console.log(e)
                error && error(error)
            })
    }
}
  • NetAddr.js
var host = 'http://192.168.0.70:8080'

var NetAddr = {
    // 個人信息
    customerInfo: host + '/Shop/CustomerInfo',
    // 我的訂單列表
    myOrderList: host + '/Shop/MyOrderList',
    // 上傳圖片
    upLoadImage: host + '/Resource/UploadImage'
}

module.exports = NetAddr
  • Connect.js
import NetUtils from './NetUtils'
import NetAddr from './NetAddr'

export default class Connect{
    /**
     *  個人信息接口
     */
    static getCustomerInfo(success){
        NetUtils.get(NetAddr.customerInfo, null,response=>{
            success && success(response)
        })
    }

    /**
     *  我的訂單列表
     */
    static  postMyOrderList(params, success){
        NetUtils.post(NetAddr.myOrderList, params, response=>{
            success && success(response)
        })
    }

   /**
    *  上傳圖片
    */
    static uploadImageFile(images, params, success){
        NetUtils.uploadFile(NetAddr.upLoadImage, images, params, response=>{
            success && success(response)
        })
     }
}

4、使用

//引入Connect
import Connect from '../../public/net/Connect'

//get請求,無參數(shù)
 getCustomerInfo() {
     Connect.getCustomerInfo(response=>{
          console.log(response)
      })
  }
 //post請求,參數(shù)為FormData形式
 postMyOrderList() {
     let params = new FormData()
     params.append('pageIndex',1)
     params.append('status',0)
     Connect.postMyOrderList(params,response=>{
          console.log(response)
     })
      //參數(shù)json形式
      //Connect.postMyOrderList({'pageIndex': 1, 'status': 0},response=>{
      //    console.log(response)
      //})
    }
 //圖片上傳,photos為圖片地址數(shù)組
uploadImage() {
   Connect.uploadImageFile(photos,null);
}

請求結(jié)果展示

image.png

5、擴展

fetch網(wǎng)絡請求是沒有超時處理的,如果需要加上timeout,請參考
讓fetch也可以timeout
[React Native 網(wǎng)絡請求封裝:使用Promise封裝fetch請求]

6、結(jié)束語

至此網(wǎng)絡請求封裝與使用都完成了,有什么問題歡迎留言探討,如果對你有幫助或者你喜歡的話,給個贊吧??!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容