uniapp uview token 鉴权登录

uniapp yekong 572℃

uniapp 微信小程序 使用uview Http请求 接口封装时 请求接口前判断是否当前接口是否需要鉴权.

封装

// 此vm参数为页面的实例,可以通过它引用vuex中的变量
import configs from './config.js'
import Qs from 'qs'

module.exports = (vm) => {
	// 初始化请求配置
	uni.$u.http.setConfig((config) => {
		/* config 为默认全局配置*/
		config.baseURL = configs.baseUrl; /* 根域名 */
		return config
	})

	// 请求拦截
	uni.$u.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
		config.header['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
		// 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
		config.data = config.data || {}
		// config.data = Qs.stringify(config.data)
		// 根据custom参数中配置的是否需要token,添加对应的请求头
		console.log(JSON.stringify(config))
		// console.log('config' + '配置')
		// console.log('获取token')
		// console.log(uni.getStorageSync('token'))
		if (config?.custom?.auth) {
			// 获取token
			// console.log('获取token2')
			if (uni.getStorageSync('openid')) {
				config.header['openid'] = uni.getStorageSync('openid')
				// 可以在此通过vm引用vuex中的变量,具体值在vm.$store.state中
			} else {
				uni.redirectTo({
					url: '/pages/login/login'
				})
			}
		}
		return config
	}, config => { // 可使用async await 做异步操作
		return Promise.reject(config)
	})

	// 响应拦截
	uni.$u.http.interceptors.response.use((response) => {
		/* 对响应成功做点什么 可使用async await 做异步操作*/
		const data = response.data
		// 自定义参数
		// const custom = response.config?.custom
		if (!data.result) {
			// 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
			uni.showToast({
				title: data.tip,
				icon: 'none'
			});
			return data === undefined ? {} : data
		}
		return data === undefined ? {} : data
	}, (response) => {
		// 对响应错误做点什么 (statusCode !== 200)
		if (response.statusCode == 401) {
			uni.clearStorageSync()
			uni.$u.route('/pages/login/login')
		}
		if (response.statusCode == 400) {
			if (process.env.NODE_ENV === 'development') {
				console.log('开发环境')
				// console.log(response)
				// console.log(response.data)
				// console.log(response.data.errors)
				try {
					for (let i in response.data.errors) {
						if (response.data.errors[i][0]) {
							uni.showToast({
								title: response.data.errors[i][0],
								icon: 'none'
							});
							throw new Error("中断循环");
						}
					}
				} catch (e) {
					console.log(e)
				};
			} else {
				console.log('生产环境')
				uni.showToast({
					title: '异常错误',
					icon: 'none'
				});
			}
		}
		return Promise.reject(response)
	})
}

api封装

const http = uni.$u.http

import qs from 'qs'
// 获取登录验证码
export const getAuthCode = (params, config = {}) => http.get('/applet/getAuthCode', config)

// 登录
export const login = (params, config = {}) => http.post('/applet/login', params, config)

post 请求实例

post 鉴权处理,如果接口需要鉴权则请求前添加如下参数

{
	custom: {
		auth: true
	}
}
getRoomList() {
	var that = this;
	getRoomList({Mobile: JSON.parse(uni.getStorageSync('phone'))}, {
		custom: {
			auth: true
		}
	}).then(res => {
		console.log(res)
		if (res.result) {
			that.list = res.data
		}
	}).catch(err => {})
},

get 请求

{
	custom: {
		auth: true
	}
}
getRoomList() {
    var that = this;
        getRoomList({
        		params: {
        			Mobile: JSON.parse(uni.getStorageSync('phone'))
        		},
        		custom: {
        			auth: true
        		}
        	}).then(res => {
        console.log(res)
        if (res.result) {
        that.list = res.data
        }
    }).catch(err => {})
},
喜欢 (0)