重慶潤雪科技有限公司(2008年至今),專注于網(wǎng)站建設、網(wǎng)站制作、網(wǎng)頁設計、小程序開發(fā)、公眾號開發(fā)、app開發(fā)的技術服務商。
每一步都修改到滿意后在付款,用價格、質量、服務說明一切。
日期:2021-04-20 14:30 瀏覽量:1258
在進行小程序制作開發(fā)的時候,微信官方提供了請求后端所用的數(shù)據(jù)接口,但是使用起來代碼太多行不利于開發(fā),索性把所有request請求都封裝成一個api.js文件,在微信小程序開發(fā)過程中就大大提高了開發(fā)速度。
小程序源生請求如下:
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' ; //本地測試環(huán)境請求域名 const baseURL = 'https://hui.runxuekeji.com' ; //線上正式環(huán)境請求域名 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('請求地址',請求參數(shù)).then(res => {
})
post請求
app.api.get('請求地址',請求參數(shù)).then(res => {
})