1, the preface

  • Wechat applet foundation
  • Be familiar withwebDeveloping friends may be rightaxiosHave a soft spot for.
  • wx.requestSecondary packaging
  • apiCentralized management and use of

2, configuration,baseUrl

  1. In general, the projectbaseUrlDomain prefix, logincode,The user informationEtc are configured inapp.jsIn the
//app.js
App({
  onLaunch: function () {
    wx.login({
      success: res => {
        if(res) code) {this. GlobalData. LoginCode = res. Code / / access code code, to further exchange for user information / / res: {/ / code:"061Zltjh1sXj6s0z96hh1Z1njh1Zltj5"
          //   errMsg: "login:ok"/ /}}else {
          console.log('Login failed! ' + res.errMsg)
        }
      }
    })
  },
  globalData: {
    userInfo: null,
    loginCode: null,
    baseUrl: 'https://... '}})Copy the code

3, encapsulationwx.request

  1. Create in the applet directoryutilsFolder, and create under the folderrequest.jsfile
// request.js
const request = options => {
  return new Promise((resolve, reject) => {
    const { data, method } = options
    if(data && method ! = ='get') {
      options.data = JSON.stringify(data)
    }
    wx.request({
      header: { 'Content-Type': 'application/json' },
      ...options,
      success: function(res) {
        if(res.data.code === 2000) {
          resolve(res.data)
        } else {
          reject(res.data)
        }
      },
      fail: function(res) {
        reject(res.data)
      }
    })
  })
}
export default request
Copy the code

4,apiCentralized management and use of

  1. Create in the applet directoryapiFolder, and create under the folderuser.jsFile (it is recommended to name the file by module)
  2. The usedaxiosThe next step should feel familiar
// user.js
import request from '.. /utils/request.js'BaseUrl = getApp().globalData.baseurl const baseUrl = getApp().globalData.baseurlexport function apiLogin(data) {
  return request({
    url: `${baseUrl}/user/login`,
    method: 'post',
    data
  })
}

export function apiGetUserInfo() {
  return request({
    url: `${baseUrl}/user/userInfo`,
    method: 'get'})}export function apiModifyUserPassword(data) {
  return request({
    url: `${baseUrl}/user/modifyPassword`,
    method: 'put',
    data
  })
}

export function apiLogout() {
  return request({
    url: `${baseUrl}/user/logout`,
    method: 'delete'})}Copy the code
  1. Use in pages
// pages/login/login.js
import { apiLogin } from '.. /.. /api/user.js'
Page({
  onLoad: function (options) {
    this.login()
  },
  login() {
    apiLogin({
      // api params
    }).then(res => {
      // handle success
    }).catch(error => {
      // handle error
    })
  }
})
Copy the code

5, stern said

  1. As it relates toES6Syntax, need to be enabled in local SettingsES6turnES5
  2. Attention should be paid to the development of small programsthisDirectivity problem.
  3. Thank you for browsing, if there is any deficiency, please correct, welcome to leave a message to discuss.