1, the preface
- Wechat applet foundation
- Be familiar with
web
Developing friends may be rightaxios
Have a soft spot for. wx.request
Secondary packagingapi
Centralized management and use of
2, configuration,baseUrl
- In general, the project
baseUrl
Domain prefix, logincode
,The user information
Etc are configured inapp.js
In 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
- Create in the applet directory
utils
Folder, and create under the folderrequest.js
file
// 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,api
Centralized management and use of
- Create in the applet directory
api
Folder, and create under the folderuser.js
File (it is recommended to name the file by module) - The used
axios
The 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
- 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
- As it relates to
ES6
Syntax, need to be enabled in local SettingsES6
turnES5
- Attention should be paid to the development of small programs
this
Directivity problem. - Thank you for browsing, if there is any deficiency, please correct, welcome to leave a message to discuss.