小程序的网络模块封装

在根目录下创建env目录,创建index.js配置并导出多个开发环境

module.exports={
    
    
  //开发环境
  Dev:{
    
    
    "BaseUrl":"https://www.develep.com"
  },
  //测试环境
  Test:{
    
    
    "BaseUrl":"https://www.test.com"
  },
  //生产环境
  Prod:{
    
    
    "BaseUrl": "https://api.douban.com"
  }
}

然后我一般会在根目录下创建一个http文件夹,在里面创建3个js文件来进行封装,分别是api,fetch,http。
在api.js中统一管理,请求的url地址

module.exports={
    
    
  "hot":"/v2/movie/in_theaters",
  "top250": "/v2/movie/top250",
  "detail": "v2/movie/subject"
}

在fetch.js中用promise对wx.request()进行封装

//封装 http
module.exports= (url, path,method, params)=>{
    
    
    return new Promise((resolve, reject) => {
    
    
      wx.request({
    
    
        url: `${
    
    url}/${
    
    path}`,
        method:method,
        data: Object.assign({
    
    }, params),
        header: {
    
     'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
        success: resolve,
        fail: reject
      })
    })
}



在http.js,根据当前环境,设置相应的baseUrl, 引入fetch中封装好的promise请求,封装基础的get\post\put\upload等请求方法,设置请求体,带上token和异常处理等;
设置对应的方法并导出;

const api = require('./api.js')
const config=require('../env/index.js');
const fetch=require('./fetch.js');
let Env='Prod';

let baseUrl = config[Env].BaseUrl;
let key ='?apikey=0b2bdeda43b5688921839c8ecb20399b'
console.log(baseUrl);
console.log(api)

function fetchGet(path,params){
    
    
  return fetch(baseUrl,path,'get',params);
}


function fetchPost(path,params){
    
    
  return fetch(baseUrl,path,'post',params);
}


module.exports={
    
    
  hot(paramas={
    
    }){
    
    
     return fetchGet(api.hot+key,paramas);
  },
  top250(params={
    
    }){
    
    
    return fetchGet(api.top250+key,params);
  },
  detail(id,params={
    
    }){
    
    
    return fetchGet(api.detail+`/${
    
    id}`+key,params)
  }
}

在全局app.js中导入http,注册到根组件

const http=require('./http/http.js')

// App.config=config[env];
App({
    
    
  http, // http.fetch

})


在组件导入,并使用;

//获取应用实例
const app = getApp();
Page({
    
    
  data: {
    
    
   list:[]
  }
onLoad: function () {
    
    
    app.http.hot().then((res)=>{
    
    
                this.setData({
    
    
            list: res.data.list
        })    })
}


猜你喜欢

转载自blog.csdn.net/wsxDream/article/details/109075195