描述:为了将页面中的方法提取出来,因此对小程序请求进行二次封装。
-
api.js(公共请求)
export const pubUrl = "https://xxx.com"//这是我要请求的数据接口的公共部分 const http = (options) =>{ return new Promise((resolve,reject) => { wx.request({ url: pubUrl + options.url, method: options.method || 'get', data: options.data || {}, header: options.header || { // 'content-type': 'application/x-www-form-urlencoded', 'content-type': 'application/json', Cookie: wx.getStorageSync("sessionid") }, success: (res => { if (res.data.code === 0) { resolve(res.data) } else if (res.data.code === 401) { wx.showToast({ title: res.data.msg, icon: 'none', complete: () => { wx.navigateTo({ url: '/pages/login/index' }) } }) } else { resolve(res.data) } }), fail: reject }) }) } module.exports = { http } 复制代码
根目录新建service文件夹,按模块新建js文件,将对应模块的接口请求放入其中,例如:
-
home.js(接口js文件,目录为service > home.js)
import http from './api.js' // 营业时间列表 const timelist = () => { return http({ method: 'get', url: '/merchant/openTime/' }) } module.exports = { timelist } 复制代码
使用:home > index.js(页面js文件)
import { timelist } from '../home'
Page({
onLoad() {
this.getData()
},
async getData() {
const {code, data, msg} = await timelist()
}
})
复制代码

© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END





![[代码走读] - 容量可扩展的channel-一一网](https://www.proyy.com/skycj/data/images/2021-06-10/0332c860927501a3ad5619becb38f02a.jpg)














![[桜井宁宁]COS和泉纱雾超可爱写真福利集-一一网](https://www.proyy.com/skycj/data/images/2020-12-13/4d3cf227a85d7e79f5d6b4efb6bde3e8.jpg)

![[桜井宁宁] 爆乳奶牛少女cos写真-一一网](https://www.proyy.com/skycj/data/images/2020-12-13/d40483e126fcf567894e89c65eaca655.jpg)