react封装一个带有路由保护功能的request函数

class MUtill {
	// 1.发送AJAX请求(带路由保护, 每次发请求都去验证有没有登录状态,需要接口里面有对应的字段才行)
	request (param) {
		return new Promise((resolve, reject) => {
			$.ajax({
				type		: param.type 		|| 'get',
				url			: param.url  		|| '',
				dataType	: param.dataType 	|| 'json',
				data 		: param.data 		|| '',
				success 	: res => {
					// 登陆成功
					if (0 === res.status) {
						typeof resolve === 'function' && resolve(res.data, res.msg)
					}
					// 没有登陆状态,强制跳转到登陆页面(需要接口里面提供一个用来判断登录状态的字段)
					else if (10 === res.status) {
						this.logout()
					}
					// 登陆失败,接口请求成功但是用户名或者密码错误
					else {
						typeof reject === 'function' && reject(res.msg, res.data)
					}
				},
				error 		: err => {
					// 这里是接口都请求错误
					// statusText是http请求错误对象err里面的东西
					typeof reject === 'function' && reject(err.statusText)
				}
			})
		})			
	}
	// 跳转到登陆页面,redirect表示从哪里跳转过来的
	logout () {
		window.location.href = '/login?redirect=' + encodeURIComponent(window.location.pathname)
	}
}
发布了32 篇原创文章 · 获赞 0 · 访问量 973

猜你喜欢

转载自blog.csdn.net/weixin_42588966/article/details/105339104