微信小程序-请求、接口拦截
目录
微信小程序-请求、接口拦截
请求拦截request.js
下面分享一下微信小程序的接口拦截
//HTTPS_HOST 接口地址。 const HTTPS_HOST = "https://www.baidu.com/wechat" function dealResult(res, resolve, reject) { console.log(‘接口response:‘,res); if (res.errMsg == ‘openDocument:ok‘) { resolve(res); } else if (res.data.status !== 400) { resolve(res.data); } else { wx.showToast({ title: res.data.message, icon: ‘none‘, duration: 2000 }) reject(res.data); } } /** * @param {Object} options 请求配置对象 参考wx实际接口文档 * @param {String} type 接口类型 默认request, downloadFile=下载文件预览,uploadFile=上传文件 * */ function request(options, type) { let params = options.data || {}; return new Promise((resolve, reject) => { console.log(token) // 通用接口拦截 if (typeof type == ‘undefined‘) { wx.request({ header: { ‘content-type‘: ‘application/json‘, ‘appSign‘: ‘wxapp‘ }, ...options, data: params, url: HTTPS_HOST + options.url, success(res) { dealResult(res, resolve, reject); }, fail(err) { wx.hideLoading() // 错误处理 wx.showModal({ title: ‘提示‘, showCancel: false, content: ‘请求超时,请检查网络!‘, success: function () { } }) // reject(err); } }); } else if (typeof type != ‘undefined‘ && type == ‘downloadFile‘) { // 下载预览 wx.downloadFile({ ...options, url: HTTPS_HOST + options.url, header: { ‘appSign‘: ‘wxapp‘ }, success(res) { const filePath = res.tempFilePath; wx.openDocument({ filePath: filePath, fileType: ‘pdf‘, success: function (res) { console.log(‘打开文档成功‘); dealResult(res, resolve, reject); }, fail(err) { console.log(‘打开文档失败:‘, err) } }) }, fail(err) { reject(err); } }) } else if (typeof type != ‘undefined‘ && type == ‘uploadFile‘) { wx.uploadFile({ ...options, url: HTTPS_HOST + options.url, header: { ‘appSign‘: ‘wxapp‘ }, success(res) { const data = res.data; dealResult(res, resolve, reject); }, fail(err) { console.log(‘err:‘,err) reject(err); }, complete(err){ console.log(‘comp:‘,err) reject(err); } }) } }) } export default request;
api接口
api.js import request from ‘../utils/request.js‘ // 普通接口 export function list(data) { return request({ url: ‘/wxList/list‘, method: ‘post‘, data }) } // 上传接口 export function uploadFile(data) { return request({ url: ‘/file/uploadFile‘, filePath: data.filePath, name: ‘file‘, formData: { ‘name‘: data.name } }, ‘uploadFile‘) } // 下载接口 export function downloadFile(id) { return request({ url: ‘/file/downloadFile‘ + ‘?id=‘ + id, method: ‘get‘, }, ‘downloadFile‘) }
如何调用
xxx.js import {list} from ‘../../api/api.js‘ list(){ list({pageNum:1,size:10,status:0}).then(res=>{ console.log(res) }).catch(err=>{ console.log(err) }) }
相关推荐
kgshuo 2020-09-25
Tomato 2020-09-10
taiyangyu 2020-09-10
CodeAndroid 2020-09-10
small 2020-07-29
sucheng 2020-07-26
zuoliangzhu 2020-07-20
CodeAndroid 2020-07-14
xiaoxubbs 2020-07-04
sucheng 2020-06-25
kgshuo 2020-06-14
意外金喜 2020-06-14
zuoliangzhu 2020-06-14
tianping 2020-06-14
hgzhang 2020-06-14
killgod 2020-06-14
戴翔的技术 2020-06-14
郴州小程序 2020-06-13