vue/cli4 axios网路请求封装 以及 登录token失效跳转页面

安装插件

npm install axios 
npm install es6-promise 

官方文档:

axios 依赖原生的 ES6 Promise 实现而被支持.
如果你的环境不支持 ES6 Promise,你可以使用 polyfill.

虽然 Axios 的文档说了支持 IE8,但文档最下面又说,前提是你的环境(浏览器)支持 promise,如果你不用关心浏览器兼容,那就不用安装 es6-promise。

把Axios 配置成 Vue插件

Axios 封装成 Vue 插件,可以直接在 Vue 组件里使用 this.xxx 的方式来调用。Axios本身并没有封装,所以这里我们自己来把它封装成 Vue 组件。

第一次封装

这里是将 Axios 封装成组件,后面会上全部代码,包含拦截器功能,验证token失效,跳转页面。

AxiosPlugin.js

require('es6-promise').polyfill()   //引入一次就行
import axios from 'axios'

// 创建 axios 实例
// 这里 export 的原因是方便组件外使用 axios
export const Axios = axios.create({
    	//baseURL: process.env.BASE_API, // node环境的不同,对应不同的baseURL
		// baseURL: 'http://localhost:8181',	
		withCredentials: true, //允许携带cookie
		timeout: 1000 * 30,
})

如果使用跨域功能,这里不需要写 baseURL,我这里使用了跨域,所以这里注释掉了。

比如我跨域的时候使用的是 /proxy。 那么我url 只需要写 /proxy/login这种方式即可。

运行时,会自动替换 /proxy 为设置的接口域名。

proxy: {/*处理跨域,本地代理转发*/
        '/proxy': {
            target: 'http://localhost:8080',  // 接口域名
            secure: false,  // 如果是https接口,需要配置这个参数
            changeOrigin: true,  //是否跨域
            pathRewrite: {
                '^/proxy': ''
            }
  },

main.js

main.js中引入并 use,from 这里有个 . ,本地,不加好像会去仓库查找。

import Vue from 'vue'
import AxiosPlugin from './plugins/AxiosPlugin'
Vue.use(AxiosPlugin)

使用:

//参数
let params = {
	'account' : 'admin',
	'password' : 'admin'
 	}
 	//网络请求
 	that.$http.post('/proxy/login', params).then(res => {
 		console.log(res)
 	}).catch(error => {
 	})

当然也可以通过 import 引用。不过封装成了组件,直接使用上面的方式就可以了

// POST
import { Axios } from 'xxx/xxx/AxiosPlugin'
Axios.post(url, params)

完整封装

关于里面的 url 配置,请看上面的第一次封装介绍。

AxiosPlugin.js

require('es6-promise').polyfill()   //引入一次就行
import axios from 'axios'

// 创建 axios 实例
// 这里 export 的原因是方便组件外使用 axios
export const Axios = axios.create({
		// baseURL: 'http://localhost:8181',
		withCredentials: true, //允许携带cookie
		timeout: 1000 * 30,	//超时时间, 毫秒级, 1000 * 多少秒就可以了
})

// 将 Axios 实例添加到 Vue 的原型对象上
export default {
		install(Vue) {
    		Object.defineProperty(Vue.prototype, '$http', { value: Axios})
		}
}

//POST 传参序列化,根据需求来。不一定用的到序列化 --> 在发送前做的操作
Axios.interceptors.request.use(config => {
		console.log('发送请求前的操作')
		// 设置以 form 表单的形式提交参数,如果以 JSON 的形式提交表单,可忽略
		//我这里使用的json数据,所以注释掉了
		// if(config.method  === 'post'){
	// JSON 转换为 FormData
		//     const formData = new FormData()
		//     Object.keys(config.data).forEach(key => formData.append(key, config.data[key]))
		//     config.data = formData
		// }

		//这里用来做验证的。
		//我这里是 uid 和 token放在了header里面请求验证。
		if (localStorage.getItem('token')) {
    		config.headers['uid'] = localStorage.getItem('uid')
	      	config.headers['token'] = localStorage.getItem('token')
		}
	return config
}, error => {
		alert("错误的传参", 'fail')
		return Promise.reject(error)
})

// 返回状态判断 (添加响应拦截器)
Axios.interceptors.response.use(res => {
		//对响应数据做些判断,如果返回的状态码代表token失效
		//跳转到 `/` 登录页。 其他的异常状态码,也可以在这里添加提示
		if (res.data.code == 4001) {
    	location.href = '/'
	}else if (res.data.code != 0) {
    	alert(res.error_msg)
    	return Promise.reject(res)
	}
		//这里直接返回的是 res.data,就是服务端返回来的数据内容。
		//可以根据自己的需求,决定返回的是 res.data,还是 res
		return res.data
}, error => {
		console.log('封装的异常: ', error)
		if(error.response.status === 401) {
    		// 401 说明 token 验证失败
    		// 可以直接跳转到登录页面,重新登录获取 token
    		location.href = '/login'
		} else if (error.response.status === 500) {
    		// 服务器错误
   	 	// do something
    	return Promise.reject(error.response.data)
		}
		// 返回 response 里的错误信息
		return Promise.reject(error.response.data)
})

调用

XX.vue

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
export default {
  name: 'defaultName',
  data() {
  	return {
  	}
  },
  methods: {
  	handleRequest() {
  		//参数
		let params = {
			'account' : 'admin',
			'password' : 'admin'
     		}
     		//网络请求
     		that.$http.post('/proxy/login', params).then(res => {
     			//我上面封装的返回的是 res.data
     			//所以这里获取到的res其实是 res.data。使用的时候,直接获取数据就可以了
     			//比如 获取 code res.code 即可
     			console.log(res)
     		}).catch(error => {
     		})
  	},
  }
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy