common文件夹下新建request.js文件

// BASE_URL只是请求url的前半部分
import BASE_URL from './url.js'

// token默认过期时间
var expiredTime = +new Date() +1800*1000

// 不需要登录的接口
const noToken = [
	'/auth/login'
];

const request = function(options={}) {
	// 判断是否需要登录
	if (!(noToken.indexOf(options.url) >= 0)) {
		// 如果不需要登录
		// 判断token是否过期,过期强制登出,不过期,正常走下一步
		var expiredTimes = uni.getStorageSync('expiresIn') || expiredTime;
		var now = +new Date()
		if(expiredTimes - now < 0){
			// token失效,重新获取
			uni.reLaunch({
				url: '/pages/login/login',
			});
		}else{
			// token有效,不需要操作
			// 获取用户 token
			let userToken = uni.getStorageSync('Authorization')
			if (!userToken) {
				uni.reLaunch({
					url: '/pages/login/login',
				});
				return false;
			} else {
				// 将 token 放入请求头中
				options.headers['Authorization'] = 'Bearer ' + userToken
			}
		}
	}
	// 请求头信息
	options.headers = {
		'content-type': 'application/json;charset=utf-8'
	};
	
	// 如果调用接口不明确不显示 loading
	if (!options.hideLoading) {
		uni.showLoading({
			title: '加载中'
		});
	}
	return uni.request({
		url: BASE_URL + options.url,
		data: options.data,
		header: options.headers,
		method: options.method,
		success: (response) => {
			console.log(response,'response')
			if (!options.hideLoading) {
				uni.hideLoading();
			}
			// console.log(response.data)
			const result = response.data
			if (result.code == 500) {
				uni.showToast({
					icon: 'none',
					title: result.message,
					duration: 1500
				})
			} else {
				options.success(result)
			}
		},
		complete: () => {
			console.log(BASE_URL + options.url);
			uni.hideLoading();
		},
		fail: (error) => {
			console.log(error,'error')
			uni.hideLoading();
			if (error && error.response) {
				showError = error => {
					let errorMsg = ''
					switch (error.status) {
						case 400:
							errorMsg = '请求参数错误'
							break
						case 401:
							errorMsg = '未授权,请登录'
							break
						case 403:
							errorMsg = '跨域拒绝访问'
							break
						case 404:
							errorMsg = `请求地址出错: ${error.config.url}`
							break
						case 408:
							errorMsg = '请求超时'
							break
						case 500:
							errorMsg = '服务器内部错误'
							break
						case 501:
							errorMsg = '服务未实现'
							break
						case 502:
							errorMsg = '网关错误'
							break
						case 503:
							errorMsg = '服务不可用'
							break
						case 504:
							errorMsg = '网关超时'
							break
						case 505:
							errorMsg = 'HTTP版本不受支持'
							break
						default:
							errorMsg = error.msg
							break
					}
				
					uni.showToast({
						title: errorMsg,
						icon: 'none',
						duration: 1000,
						complete: function() {
							setTimeout(function() {
								uni.hideToast();
							}, 1000);
						}
					});
				}
				showError(error.response);
			}
		},
		timeout:30000
	})
}

export default request;

common文件夹下新建url.js文件

var BASE_URL = ""

if(process.env.NODE_ENV === 'production'){
    // 生产环境
    BASE_URL = 'http://' + window.location.host + '/washer'
}else{
    // 开发环境
    BASE_URL = 'http://' + window.location.host
}

export default BASE_URL

使用,login.js

import request from './request.js'

export function applogin(query) {
	return request({
		url: '/auth/login',
		method: 'POST',
		data: query.data,
		success:query.success
	})
}

app.vue 页面

import {applogin} from '@/common/login.js'
methods:{
bindLogin() {
	if (this.loginForm.username.length < 0) {
		uni.showToast({
			icon: 'none',
			title: '请输入账号'
		});
		return;
	}
	if (this.loginForm.password.length < 0) {
		uni.showToast({
			icon: 'none',
			title: '请输入密码'
		});
		return;
	}
	applogin({
		data:this.loginForm,
		success: (res) => {
			uni.setStorageSync("Authorization", res.data.access_token)
			uni.setStorageSync("expiresIn", new Date() + res.data.expires_in * 1000)
			// 进入首页
			this.toMain(this.account);
		},
		// 	uni.showToast({
		// 		icon: 'none',
		// 		title: '用户账号或密码不正确',
		// 	});
	})
	}
}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐