1. 配置URL地址文件
项目根目录下生成一个文件夹 config ,文件夹中生成一个 config.js 文件。
1 2 3 4 5
| module.exports = { dev:"www.xxxxxx.xxx", test:"www.xxxxxx.xxx", pro:"www.xxxxxx.xxx" }
|
2. 请求拦截、响应拦截
项目根目录下生成一个文件夹 utils ,文件夹中生成一个 request.js 文件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| import config from "/config/config.js";
let baseUrl = config.test;
module.exports = { fetch: (url, data = {}, option = {}) => { let { loading = true, toast = true, method = 'get' } = option; let header = { 'content-type': 'application/x-www-form-urlencoded', 'token':getApp().globalData.token }; return new Promise((resolve, reject) => { if (loading) { uni.showLoading({ title: "加载中...", mask: true }) }; uni.request({ url: baseUrl + url, data, method, header, success: function(result) { let res = result.data; if (res.code == 200) { if (loading) { uni.hideLoading(); } resolve(res); } else if (res.code == 203) { uni.redirectTo({ url: '/login/login' }) } else { if (toast) { uni.showToast({ mask: true, title: res.msg, icon: 'none' }) } else { uni.hideLoading() } resolve(res); } }, fail: function(e = { code: -1, msg: errMsg, errMsg }) { console.log(e) let msg = e.errMsg; if (msg == "request:fail timeout") { msg = "请求超时,请稍后再试"; } else if (msg == "request:fail" || msg == "") { msg = "请求失败,再试试" } uni.showToast({ title: msg, icon: "none" }) reject(e); } }) }) }, }
|
3. 引入文件
在 main.js 中引入写好的 request.js 文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import Vue from 'vue' import App from './App' import request from "./utils/request.js";
Vue.prototype.get = request.fetch; Vue.prototype.post = (url, data) => { return request.fetch(url, data, { method: "post" }); }; Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({ ...App });
app.$mount()
|
4. 请求的方法 get 、post
直接调用 this.get() 或者直接调用 this.post() 就可以了
1 2 3 4 5 6 7 8 9 10
| login() { let data={...}; this.get("/api/login",data).then(res=>{ console.log(res); }) this.post("/api/login",data).then(res=>{ console.log(res); }) }
|