-
新建
utils/http.js文件export default const http = { interceptor:{ request:(config)=>{ return config; }, response:(response)=>{ let {code,message,data} = response.data; if(code !== 200){ console.log(message); } return data; } }, request(options){ let header = { 'Content-Type': 'application/json;charset=UTF-8' } const baseUrl = process.env.VUE_APP_URL; options.url = baseUrl + options.url; options.method = options.method || 'GET'; options.data = options.data || {}; options.header = options.header || header; options.loading = options.loading === false ? false : true; options.requestTime = options.requestTime || 500; options.dataType = options.dataType || 'json'; let loadingStatus = true; setTimeout(() => { if (loadingStatus && options.loading) { uni.showLoading({ title: "加载中", mask: true }) } },options.requestTime) return new Promise((resolve, reject) => { if (!this.interceptor.request(options)) { return; } //请求接口日志记录 _reqlog(options) uni.request({ url: options.url, method: options.method, data: options.data, header: optioons.header, dataType: options.dataType, complete: (response) => { let statusCode = response.statusCode; let res = this.interceptor.response(response); if (this.interceptor.response) { if (statusCode == 200) { //接口响应日志 _reslog(res) resolve(res) }else { reject(res) } if (loadingStatus && options.loading) { uni.hideLoading(); } loadingStatus = false; } } }) }); }, get(url,data,options){ if (!options) options = {} options.url = url options.data = data options.method = 'GET' return this.request(options) }, post(url, data, options) { if (!options) options = {} options.url = url; options.data = data; options.header = options.header || { 'content-type': 'application/json;charset=UTF-8' } options.method = 'POST' return this.request(options) }, postForm(url, data) { return this.post(url, data, { header: { 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8' } }) } } /** * 请求接口日志记录 */ function _reqlog(req) { if (process.env.NODE_ENV === 'development') { console.log("请求地址:" + req.url) if(req.data){ console.log("请求参数:" + JSON.stringify(req.data)) } } } /** * 响应接口日志记录 */ function _reslog(req) { let _statusCode = res.code; if (process.env.NODE_ENV === 'development') { console.log("响应结果:" + JSON.stringify(res)) } } -
在
mian.js中引入... import http from '@/utils/http.js' //挂载到原型 Vue.prototype.$http = http; -
使用方法
this.http.get('/apis/data').then( data =>{ console.log(data) })