Paquete de módulo de red del subprograma

Cree un directorio env en el directorio raíz, cree una configuración index.js y exporte múltiples entornos de desarrollo

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

Luego, generalmente creo una carpeta http en el directorio raíz y creo archivos 3 js en ella para encapsularlos, a saber, api, fetch y http.
Gestión unificada en api.js, la dirección URL solicitada

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

Use la promesa para encapsular wx.request () en 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
      })
    })
}



En http. etc .;
establecer el método correspondiente y exportar;

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

Importe http en el archivo app.js global y regístrese en el componente raíz.

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

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

})


Importar y usar en el componente;

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


Supongo que te gusta

Origin blog.csdn.net/wsxDream/article/details/109075195
Recomendado
Clasificación