微信开发 封装全局request请求
在utils 新建一个 api.js 文件
打开文件 封装请求
const app = getApp()
const bastUrl = 'https://api-hmugo-web.itheima.net/api/public/v1'
const Request = (url, options) => {
return new Promise((resolve, reject) => {
wx.request({
url: `${bastUrl}${url}`,
method: options.method,
data:
options.method === 'GET' ? options.data : JSON.stringify(options.data),
header: {
'Content-Type': 'application/json; charset=UTF-8',
},
success(request) {
// 根据自己的接口写
if (request.data.meta.status == 200) {
resolve(request.data.message)
} else {
reject(request.data.message)
}
},
fail(error) {
reject(error)
console.log(error)
},
})
})
}
const get = (url, options = {}) => {
return Request(url, { method: 'GET', data: options })
}
const post = (url, options) => {
return Request(url, { method: 'POST', data: options })
}
module.exports = {
get,
post,
}
打开 app.js 文件
import { get, post } from './utils/api'
App({
onLaunch() {
wx.get = (url, options) => {
return get(url, options)
}
wx.post = (url, options) => {
return post(url, options)
}
}
})
使用方法
/**
* 获取轮播图
* @param {*} options
*/
getSwiper() {
wx.get('/home/swiperdata')
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.getSwiper()
},
接口文档示例