前言
小程序有自带的ajax,且也做了相关的跨域处理,基本格式放在下边
wx.request({
url: 'test.php', //仅为示例,并非真实的接口地址
data: {
x: '',
y: ''
},
header: {
'content-type': 'application/json' // 默认值=》请求他
},
success (res) {
console.log(res.data)
}
})
1.先封装微信的request
新建一个文件,我这里放在了utils文件夹里新建的util.js的文件里
以下代码默认是get请求,后期需要post请求可以直接在调接口的文件中写成"POST"
function request(url, data = {}, method = "GET") {
return new Promise(function(resolve, reject) {
wx.request({
url: url,
data: data,
method: method,
header: {
'Content-Type': 'application/json',
'X-Litemall-Token': wx.getStorageSync('token')
},
success:function(res){
console.log(res)
},
fail:funtion(res){
}
})
})
})
2.把所有用得到的接口也封装成函数
然后在config文件夹中,新建api.js文件,把自己会遇到的所有接口都放在这里边,包括本地测试或者线上测试的环境(根目录)都放在里边
//api.js
var WxApiRoot = 'http://xxxxxx/';//根目录(本地测试接口的根目录或是线上测试接口的根目录)
module.exports = {
// 自定义接口名:后台接口链接(记得加上根目录)
GetAllData:WxApiRoot + 'home/index'
}
3.在需要用到接口的js页面引入即可使用
var util = require('../../utils/util.js');
var api = require('../../config/api.js');
//util调用api.js文件的GetAllData方法
util.request(api.GetAllData, {
grouponId: grouponId
}).then(function(res) {
console.log(res)
})