小程序官方有自己网络请求的api,但这种写法不好去维护,耦合度太高,也容易出现回调地狱。
wx.request({
url: 'test.php', //仅为示例,并非真实的接口地址
data: {
x: '',
y: ''
},
header: {
'content-type': 'application/json' // 默认值
},
success (res) {
console.log(res.data)
}
})
封装:
- 新建一个api文件,里面创建一个configUrl.js和request.js两个js文件。
- configUrl.js里是用来放我们请求的域名的
export default const configUrl = 'https://api.unit.com';
- request.js是用来封装请求的文件。这里我们使用es6的promise进行封装。首先引入configUrl ,然后在官方api基础上进行封装:
import configUrl from './configUrl.js'
export default function request(options){
retun new Promise((reslove,reject)=>{
wx.request({
url: configUrl+options.url,
method: options.method||'get',
data: options.data||{},
header: {
'content-type': 'application/json',
'Authorization': 'Bearer ' + wx.getStorageSync('token')
},
success (res) {
reslove(res)
},
fail(err){
reject(err)
}
})
})
}
- 在页面调用封装的请求
import request from '/api/request.js'
request({
url:'/article-list',
method:'get',
data:{type:'social'}
}).then(res=>{
}).catch(err=>{
})