WeChat applet uses promise to encapsulate wx.request()

1. Directory structure

Mini Program Directory Structure

First create index.js in the env directory, configure the development environment inside and export it

//配置不同的开发环境
module.exports={
    
    
  //开发环境
  Dev:{
    
    
    baseUrl:'http://123.207.32.32:8000/api/h8', //开发环境的接口
  },
  //测试环境
  Test:{
    
    
    baseUrl:'http://www.test.com'
  },
  //生产环境
  Prod:{
    
    
    baseUrl:'http://www.api.douban.com'
  }
}

Enter the http directory and define all request URL addresses uniformly in config.js, which is convenient for maintenance and management

//定义请求路径并抛出对象
module.exports={
    
    
  "banner":"/home/multidata",
  "list":"/home/list"
}

Throw a request function in request.js, the return value of the function is a promise object

//封装wx.request()网络模块

//抛出一个函数 这个函数会返回一个promise对象
module.exports=(url,method,data)=>{
    
    
  let p=new Promise((resolve,reject)=>{
    
    
    wx.request({
    
    
      url: url,       //请求路径
      method:method,    //请求方式
      data:Object.assign({
    
    },data),   //请求参数,使用浅拷贝
      header:{
    
    "Content":"application/text"},  //请求头,默认参数
      success(res){
    
       //成功的回调函数
        resolve(res)
      },
      fail(err){
    
        //失败的回调
        reject(err)
      }
    })
  })

  return p;
}

Entry function index, here is the entry file, so that others will know what the folder is used for and how to use it.

//入口函数,引入环境变量,路径和方法在此处统一调用
const Env=require('../env/index')
const Url=require('./config')
const Request=require('./request')

console.log(Request);

//确定当前环境
let baseUrl=Evn.Dev.baseUrl
//如果接口需要token鉴权,获取token
let token=wx.getStorageSync('token') //获取本地存储的token

//请求的函数
//banner请求
function banner(){
    
    
  //调用该方法,传递路径(环境前缀+路径),方式,参数 函数结果会返回一个promise对象
  return Request(baseUrl+Url.banner,'get',{
    
    })
}
//xxx请求 直接照搬就行

//将封装好的方法抛出
module.exports={
    
    
  banner
}

The last step is to import index in the global app.js and register to the root component

//app.js

//引入http请求模块
const http=require('./http/index')

//直接在App方法里简单粗暴挂载一个http方法,挂上去就能用
App({
    
    
  http,
})

how to use

//哪个文件要发送请求,就在头部引入app.js里面app这个全局对象
const app=getApp()
//使用方法简单粗暴,括号内可以传参数
app.http.banner().then(res=>{
    
    
	console.log(res)
})

At a glance, it is basically the same as the idea of ​​Vue encapsulating axios-
separately define the path and request function, call it in index.js, and mount the method to the global object.
In the future, you only need to modify the corresponding request path or add a new request method when modifying.

Guess you like

Origin blog.csdn.net/weixin_51198863/article/details/111377514