Secondary encapsulation of WeChat applet interface

The main idea: to
Insert picture description here
realize the splicing of interfaces: divided into "fixed interface" splicing and "free interface" splicing
How to realize interface splicing: divided into three splicing:
1. Create an env.js, and write your own default interface address in it. Define some interfaces for configuring other environments
eg:baseUrl:"https://api.it120.cc"
2. Create a request.js, you can set some of your own default configuration in it
eg:const subName ='set at will to see what type of demand is'
the let _url = ${baseUrl}/${isDoMain?subName:''}${url}
3. create an api interface in front of the stitching inside the interface and add the interface to the company's address, and can accept the passed parameters in this file inside
eg: // goods List
getList:()=>{ return request("/shop/goods/list","",{},true) }, the main code is as follows: env.js



module.exports={
   //开发环境url
   dev:{
    baseUrl:"http://localhost:3000"
  },
  //测试环境得url
  test:{
    baseUrl:"http://www.test.com"
  },
  // 线上环境url
  prod:{
    baseUrl:"https://api.it120.cc"
  }
}

request.js

const {baseUrl} = require("./env").prod
const subName = '随意配置的'
module.exports={
  request:(url,method="GET",data={},isDoMain)=>{
    wx.showLoading()
    let _url = `${baseUrl}/${isDoMain?subName:''}${url}`
    return new Promise((resolve,reject)=>{   
      wx.request({
        url: _url,
        data:data,
        method:method,
        header:{
          'content-type':'application/x-www-form-urlencoded'
        },
        success:res=>{      
          let {code} = res.data           
           if(code===0||code===700){
             resolve(res);
             wx.hideLoading()
           }else{
             wx.showToast({
               title: '请先登录',
               icon:'none'
             })        
          }
        },
        fail:res=>{
          reject('接口有误请检查')
        }
      })
    })
  }
}

api.js configuration interface main file

const {request} = require("./request")
module.exports={
  // 商品列表
   getList:()=>{
      return request("/shop/goods/list","",{},true)
    },
    // 详情页
  getDetail:(id)=>{
    return request("/shop/goods/detail","",{id},true)  // 需要传递参数的
  },
  }

How to call?

const {getList,getDetaill} = require("../../http/api")

how to use?

getList().then((res)=>{
       console.log(res.data.data)   // 获取的数据
      this.setData({
           list:res.data.data
       })   // 把获取到的数据进行更新
     })

Ginseng?
eg: let token=wx.getStorageSync('token')
getList(token).then((res)=>{})
Pass parameters when calling the method, and accept them in the api.js file

Guess you like

Origin blog.csdn.net/lqlq54321/article/details/106911615