1.在uview官网安装u-view,在main.js中引入uView

 

npm install uview-ui

 main.js

// 引入全局uView
import uView from 'uview-ui'
Vue.use(uView);

2:在common文件中新建http.interceptor.js文件

// 这里的vm,就是我们在vue文件里面的this,所以我们能在这里获取vuex的变量,比如存放在里面的token
// 同时,我们也可以在此使用getApp().globalData,如果你把token放在getApp().globalData的话,也是可以使用的
const install = (Vue, vm) => {
	Vue.prototype.$u.http.setConfig({
		baseUrl: Vue.prototype.baseUrl,
		// 如果将此值设置为true,拦截回调中将会返回服务端返回的所有数据response,而不是response.data
		// 设置为true后,就需要在this.$u.http.interceptor.response进行多一次的判断,请打印查看具体值
		// originalData: true, 
		// 设置自定义头部content-type
		// header: {
		// 	'content-type': 'xxx'
		// }
		showLoading: true, // 是否显示请求中的loading
		loadingText: '请求中...', // 请求loading中的文字提示
	});
	// 请求拦截,配置Token等参数
	Vue.prototype.$u.http.interceptor.request = (config) => {
		// config.header.Token = 'xxxxxx';
		
		if(config.url.search(`/wx/user/${Vue.prototype.appid}/login`)===-1){
			config.header.Authorization ="wx "+uni.getStorageSync("token")
		}else{
			config.header.Authorization ="";
		}
		// 方式一,存放在vuex的token,假设使用了uView封装的vuex方式,见:https://uviewui.com/components/globalVariable.html
		// config.header.token = vm.token;
		
		// 方式二,如果没有使用uView封装的vuex方法,那么需要使用$store.state获取
		// config.header.token = vm.$store.state.token;
		
		// 方式三,如果token放在了globalData,通过getApp().globalData获取
		// config.header.token = getApp().globalData.username;
		
		// 方式四,如果token放在了Storage本地存储中,拦截是每次请求都执行的,所以哪怕您重新登录修改了Storage,下一次的请求将会是最新值
		// const token = uni.getStorageSync('token');
		// config.header.token = token;
		
		return config; 
	}
	// 响应拦截,判断状态码是否通过
	Vue.prototype.$u.http.interceptor.response = (res) => {
		// 如果把originalData设置为了true,这里得到将会是服务器返回的所有的原始数据
		// 判断可能变成了res.statueCode,或者res.data.code之类的,请打印查看结果
		if(res.code == 403) {
			// uni.setStorageSync('token','');
			// window.location.href = "https://ycdw.likecy.cn/index/user/login";
			// 如果把originalData设置为了true,这里return回什么,this.$u.post的then回调中就会得到什么
			// return res.data;  
		} 
		return res;  
		// if(res.code == 1) {
		// 	// 如果把originalData设置为了true,这里return回什么,this.$u.post的then回调中就会得到什么
		// 	return res.data;  
		// } else return false;
	}
}

export default {
	install
}

在main.js中加入appid和baseUrl属性,以及引入拦截器

main.js:

import Vue from 'vue'
import App from './App'

Vue.prototype.appid ="wxd1bbb09cf5722b50"
Vue.prototype.baseUrl ="http://1.14.104.10/prod-api"
// 引入全局uView
import uView from 'uview-ui'
Vue.use(uView);

const app = new Vue({
	...App,
})

// http拦截器,将此部分放在new Vue()和app.$mount()之间,才能App.vue中正常使用
import httpInterceptor from '@/common/http.interceptor.js';
Vue.use(httpInterceptor, app);

// http接口API抽离,免于写url或者一些固定的参数
import httpApi from '@/common/http.api.js';
Vue.use(httpApi, app);
App.mpType = 'app'
app.$mount()

3:API集中管理

这里说的集中管理,是指把各个请求,统一放到一个文件中进行管理.

这样的好处是不用每次调用this.$u.get时都需要传入url参数,一些固定的请求参数也可以不用显式的传入.

在common文件创建http.api.js文件

// 如果没有通过拦截器配置域名的话,可以在这里写上完整的URL(加上域名部分)
// let hotSearchUrl = '/ebapi/store_api/hot_search';
// let indexUrl = '/ebapi/public_api/index';
// let submitFromRepairUrl = '/cqdw.Wxuser/submitThings';

// 此处第二个参数vm,就是我们在页面使用的this,你可以通过vm获取vuex等操作,更多内容详见uView对拦截器的介绍部分:
// https://uviewui.com/js/http.html#%E4%BD%95%E8%B0%93%E8%AF%B7%E6%B1%82%E6%8B%A6%E6%88%AA%EF%BC%9F
const install = (Vue, vm) => {
	// 此处没有使用传入的params参数
	let login = (params = {}) => vm.$u.get(`/wx/user/${params.appid}/login`, params);
	let gettext = (params = {}) => vm.$u.get(`/wx/cms/school/103`, params);
	let auth = (params = {}) => vm.$u.post(`/wx/user/${params.appid}/postAuth`, params);
	vm.$u.api = {
		login,
		auth,
		gettext
	};
}

export default {
	install
}

我们上面是创建和配置了http.api.js,接下来需要在main.js中进行挂载,如果您配置了拦截器,这部分的引入代码,需要写在拦截器引入的后面:

main.js

// http拦截器,将此部分放在new Vue()和app.$mount()之间,才能App.vue中正常使用
import httpInterceptor from '@/common/http.interceptor.js';
Vue.use(httpInterceptor, app);

// http接口API抽离,免于写url或者一些固定的参数
import httpApi from '@/common/http.api.js';
Vue.use(httpApi, app);
App.mpType = 'app'
app.$mount()

4.我们使用uniapp的loginAPI

uni.login({
				  provider: 'weixin',
				  success: function (loginRes) {
				    console.log("code:",loginRes.code);
					that.$u.api.login({
						appid:that.appid,
						code:loginRes.code,
						token:uni.getStorageSync("token")
					}).then(res=>{
						console.log("res",res);
						uni.setStorageSync("token",res.data.token);
					})
				  }
		  });

不过在此之前,需要在manifest.json文件配置微信小程序的AppID

uniapp css 判断安卓还是ios uniapp全局判断登录_拦截器

login.vue

<template>
	<view class="app">
		<div class="imgDiv">
			<image :src="logo" mode="aspectFill"></image>
		</div>
		<button type="primary" open-type="getUserInfo" @getuserinfo="wxLogin">
			<view class="item column center">
				授权登录
			</view>
		</button>
		<br/>
		<button type="primary" style="padding-top: 20px;"  @click="getUserInfo">
			<view>
				获取用户信息
			</view>
		</button>
	</view>
</template>
<script>
	import logo from '@/static/login/logo.png'
	var that;
	export default {
		data() {
			return {
				logo
			}
		},
		onLoad() {},
		methods: {
			wxLogin()
			{
				that = this;
				uni.login({
				  provider: 'weixin',
				  success: function (loginRes) {
				    console.log("code:",loginRes.code);
					that.$u.api.login({
						appid:that.appid,
						code:loginRes.code,
						token:uni.getStorageSync("token")
					}).then(res=>{
						console.log("res",res);
						uni.setStorageSync("token",res.data.token);
					})
				  }
				});
			},
			getUserInfo(){
				that = this;
				uni.getUserProfile({
				 desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
				  success: function (infoRes)
				  {
					console.log(infoRes);
				    console.log('用户昵称为:' + infoRes.userInfo.nickName);
					var data ={
						wxName:infoRes.userInfo.nickName,
					}
					that.$u.api.auth(data).then(res=>{
						console.log(res);
					})
				  },
				  fail:infoRes =>
				  {
					   console.log(infoRes);
				  }
				});
			}
		}
	}
</script>


<style scoped lang='scss'>
	.app {
		text-align: center;
		padding: 20px;
	}

	.imgDiv {
		width: 200rpx;
		height: 200rpx;
		margin: 50px auto;

		image {
			width: 100%;
			height: 100%;
			border-radius: 50%;
		}
	}
	.mt20 {
		margin-top: 20px;
	}
</style>

uni.login之后,会携带一个token,请求某些页面需要携带token进行访问,因此需要写到vuex里面

store:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
	state:
	{
		userInfo:{},
		needAuth:true,//是否需要授权
		isLogin:false,//是否登录
	},
	getters:
	{
		getUserInfo(state)
		{
			return state.userInfo
		},
		getNeedAuth(state)
		{
			return state.needAuth
		},
		getIsLogin(state)
		{
			return state.isLogin
		}
	},
	actions:
	{
		Login(context)
		{
			uni.login({
			  provider: 'weixin',
			  success: function (loginRes) {
			    console.log("code:",loginRes.code);
				Vue.prototype.$u.api.login({
					appid:Vue.prototype.appid,
					code:loginRes.code,
					token:uni.getStorageSync("token")
				}).then(res=>{
					console.log("res",res);
					uni.setStorageSync("token",res.data.token);
					if(res.msg ==="登录成功")
					{
						context.commit('setUserInfo',res.data.user);
						context.commit('setNeedAuth',false);
						context.commit('setIsLogin',true);
					}
					
				})
			  }
			});
		},
		getUserInfo(context)
		{
			uni.getUserProfile({
			 desc: '完善用户资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
			  success: function (infoRes)
			  {
			    console.log('用户昵称为:' + infoRes.userInfo.nickName);
				context.commit('setUserInfo',
				{
					avatarUrl:res.userInfo.avatarUrl,
					wxName:res.userInfo.nickName,
					// deptId
					// country:res.userInfo.country,
					// gender:res.userInfo.gender,
					// language:res.userInfo.language,
					
					// province:res.userInfo.province
				});
				// var user ={
				// 	wxName:infoRes.userInfo.nickName,
				// 	avatarUrl:res.userInfo.avatarUrl
				// };
				Vue.prototype.$u.api.auth(context.state.userInfo).then(res=>{
					console.log(res);
				})
			  },
			  fail:infoRes =>
			  {
				   console.log(infoRes);
			  }
			});
			
		}
	},
	mutations:
	{
		setUserInfo(state,uerInfo)
		{
			state.userInfo = UserInfo
		},
		setNeedAuth(state,needAuth)
		{
			state.needAuth = needAuth
		},
		setIsLogin(state,isLogin)
		{
			state.isLogin = isLogin
		},
	}
})
export default store