Network module package of applet

Create an env directory in the root directory, create an index.js configuration and export multiple development environments

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

Then I usually create an http folder in the root directory, and create 3 js files in it for encapsulation, namely api, fetch, and http.
Unified management in api.js, the requested url address

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

Use promise to encapsulate wx.request() in fetch.js

//封装 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
      })
    })
}



In http.js, according to the current environment, set the corresponding baseUrl, introduce the promise request encapsulated in fetch, encapsulate the basic get\post\put\upload and other request methods, set the request body, bring token and exception handling, etc.;
set The corresponding method and export;

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)
  }
}

Import http in the global app.js and register to the root component

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

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

})


Import and use in the component;

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


Guess you like

Origin blog.csdn.net/wsxDream/article/details/109075195