企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# uniapp request请求封装包含token兼容多端,简单易用 1、首先我们在新建好的uniapp项目中新建一个文件夹common,再建一个request.js文件 ![](https://img-blog.csdnimg.cn/20201209103751803.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTQ2Nzg1ODM=,size_16,color_FFFFFF,t_70) 2\. 在request.js放入以下代码 ``` var apiUrl = ''; //放入后台接口的url // #ifdef H5 var baseUrl = ''; if (process.env.NODE_ENV === 'development') { //本地环境,即开发环境 baseUrl = '/api' } else { //线上环境 baseUrl = apiUrl } // #endif //封装request请求 const sendRequest = (url, method = 'GET', data = {}, contentType) => { //判断header提交数据类型 let types = ''; if (method == 'POST' && !contentType) { types = 'application/x-www-form-urlencoded' } else if (method == 'POST' && contentType) { types = contentType } else { types = 'application/json'; } // #ifdef H5 var bases = baseUrl + '/' + url; // #endif // #ifndef H5 var bases = apiUrl + '/' + url; // #endif var token = uni.getStorageSync('token') || ''; return new Promise(function(resolve, reject) { uni.request({ url: bases, data: data, method: method, header: { 'Content-Type': types, 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Authorization': token }, success(res) { if (res.header.authorization) { uni.setStorageSync('token', res.header.authorization); } else { var code = res.statusCode; switch (code) { case 401: uni.showModal({ title: '登录提示', content: '身份已过期,请重新登录后再来操作!', success:ress => { if (ress.confirm) { uni.redirectTo({ url:'/pages/WxLogin/Accredit' }) } } }) break; default: resolve(res); break; } } }, fail(err) { reject(err); } }) }) } module.exports.sendRequest = sendRequest ``` 3、在main.js中全局挂载 ``` import Vue from 'vue' import App from './App' import http from './common/js/request.js' Vue.config.productionTip = false Vue.prototype.$urls = ""; //线上url接口 Vue.prototype.$http = http; App.mpType = 'app' const app = new Vue({ ...App }) app.$mount() ``` 4、在页面中使用 **get方法** ``` //url-后台接口 //data-参数,传递给后台的参数 this.$http.sendRequest(url, 'GET', { data:data }).then(res => { //成功回调 }).catch(err => { //请求失败 console.log(err) }) ``` **POST方法** ``` //url-后台接口 //data-参数,传递给后台的参数 this.$http.sendRequest(url,'POST',{ data:data }).then(res => { //成功回调 }).catch(err => { //请求失败 }) ```