日期:2021-04-20 14:30 浏览量:1684
在进行小程序制作开发的时候,微信官方提供了请求后端所用的数据接口,但是使用起来代码太多行不利于开发,索性把所有request请求都封装成一个api.js文件,在微信小程序开发过程中就大大提高了开发速度。
小程序源生请求如下:
wx.request({
url: 'test.php', //仅为示例,并非真实的接口地址
data: {
x: '',
y: ''
},
header: {
'content-type': 'application/json' // 默认值
},
success (res) {
console.log(res.data)
}
})封装后的api.js文件代码:
//const baseURL = 'http://www.huishou.com' ; //本地测试环境请求域名
const baseURL = 'https://hui.runxuekeji.com' ; //线上正式环境请求域名
const http = ({ url = '', params = {},show = false, ...other } = {}) => {
if ( show ) {
wx.showLoading({
title: ''
})
}
let time = Date.now()
return new Promise((resolve, reject) => {
wx.request({
url: getUrl(url),
data: params,
header: getHeader(),
...other,
complete: (res) => {
if (show) {
wx.hideLoading()
}
if (res.statusCode >= 200 && res.statusCode < 300) {
resolve(res.data)
} else {
reject(res)
}
}
})
})
}
const getUrl = url => {
if (url.indexOf('://') == -1) {
url = baseURL + url
}
return url
}
const getHeader = () => {
try {
var token = wx.getStorageSync('openid')
if (token) {
return { 'openid': token }
}
return {}
} catch (e) {
return {}
}
}
module.exports = {
baseURL,
get(url, params = {} ,show = false) {
return http({
url,
params,
show
})
},
post(url, params = {}, show = false) {
return http({
url,
params,
show,
method: 'post'
})
},
put(url, params = {}, show = false) {
return http({
url,
params,
show,
method: 'put'
})
},
myDelete(url, params = {}, show = false) {
return http({
url,
params,
show,
method: 'delete'
})
}
}api.js请求的使用如下:
get请求
app.api.get('请求地址',请求参数).then(res => {
})
post请求
app.api.get('请求地址',请求参数).then(res => {
})