1、配置app.js
App({
onLaunch: function() {
},
globalData: {
userInfo: null,
loginCode: null,
version: '1.0.0',
baseUrl:'https://www.test.com' //根据自己的请求地址配置
}
})
2、封装request
const app = getApp();
const baseURL = app.globalData.baseUrl; //引用baseUrl
const Request = (options) => {
return new Promise((resolve,reject) => {
wx.request({
url: baseURL + options.url || '',
data: options.data || {},
method: options.method || 'POST',
header: { 'Authorization': "" }, //设置请求头
responseType: options.responseType || "text",
timeout: 15000,
success(res) {
resolve(res.data);
},
fail(res) {
reject(res);
}
})
})
};
module.exports = {
Request
};
3、封装API
const request = require('../api/request'); //引用封装的request
const HTTP = {
systemDetails(url) {
return request.Request({
url: '/test/system/details'+url,
method: 'get'
})
},
systemList(data,url) {
return request.Request({
url: '/test/system/list'+url,
method: 'post',
data:data
})
},
}
module.exports = HTTP;
4、使用方法
import HTTP from "../../api/api"; //引用封装的api
const app = getApp()
Page({
data: {
pageNum:1,
pageSize:10,
info: {},
list:[],
},
// 接口未封装示例
test() {
var that = this
wx.request({
url: 'https://www.test.com/test/system/details',
// data: {},
method: 'GET',
header: {
'Authorization': '' // 默认值
},
success: function (res) {
console.log(res)
that.setData({ info: res.data.data })
}
})
},
// 接口已封装示例(get)
systemDetails() {
var that = this
HTTP.systemDetails(`?pageNum=${that.data.pageNum}&pageSize=${that.data.pageSize}`)
.then(res => {
console.log(res)
that.setData({ info: res.data }) //渲染data
});
},
//接口已封装示例(post)
systemList() {
var that = this
//这里传了两个参,可根据需要修改,不传则都为空
HTTP.systemList({
"id": 1,
"user": 'zhangsan'
},`?pageNum=${that.data.pageNum}&pageSize=${that.data.pageSize}`)
.then(res => {
console.log(res)
that.setData({ list: res.data }) //渲染data
});
},
//获取当前行id示例
onItemClick(event) {
console.log(event.currentTarget.dataset.postidIdex) //获取id
let postidIdex = event.currentTarget.dataset.postidIdex
//页面跳转
tt.navigateTo({
url: `/pages/details/details?postidIdex=${postidIdex}`,
//demo示例,一般路径形式:/pages/detail/detail?key=${value}
});
},
//页面加载请求
onLoad: function () {
this.test()
this.systemDetails()
this.systemList()
},
})