首先请务必已仔细阅读 Axios 文档并熟悉 JWT:vue
安装ios
npm install axios
npm install es6-promise
为何要安装 promise polyfill ?虽然 Axios 的 GitHub 主页开头说了支持 IE8,但文档最下面又说,前提是浏览器支持 promise,若是你不用关心浏览器兼容,那就不用安装 es6-promise。es6
用过 vue-resource 的都知道,它自己封装成了 Vue 插件,能够直接在 Vue 组件里使用 this.$http
, Axios 自己虽然没有封装,但咱们也能够手动把它封装成 Vue 插件。
具体原理请看 Vue框架引入JS库的正确姿式,下面我就用代码演示一下:npm
AxiosPlugin.js↓axios
require('es6-promise').polyfill() // 引入一次就行 import axios from 'axios' // 建立 axios 实例 // 这里 export 的缘由是方便组件外使用 axios export const Axios = axios.create({ baseURL: 'xxx', timeout: 5000, }) // 将 Axios 实例添加到Vue的原型对象上 export default { install(Vue) { Object.defineProperty(Vue.prototype, '$http', { value: Axios }) } }
main.jssegmentfault
import Vue from 'vue' import AxiosPlugin from 'xxx/xxx/AxiosPlugin' Vue.use(AxiosPlugin)
在组件内部后端
/ GET 获取用户信息 // http://xxxx/user?a=1&b=2 const data = { params: { a: 1, b: 2, } } this.$http.get(url, data).then(res => { console.log(res) }) // POST 请求 const data = { a: 1, b: 2, } this.$http.post(url, data).then(res => { console.log(res) })
在组件外部promise
// POST import { Axios } from 'xxx/xxx/AxiosPlugin' Axios.post(url, data)
以上是 Axios 的基本配置,下面咱们说一下如何以 x-www-form-urlencoded 格式发送表单数据、设置 JWT 的 token 、以及 token 过时自动登陆。浏览器
废话很少说,直接上完整的代码,伸手党的福利
AxiosPlugin.js服务器
require('es6-promise').polyfill() import axios from 'axios' export const Axios = axios.create({ baseURL: 'http://xxxxx/', timeout: 10000, }) //POST传参序列化(添加请求拦截器) // 在发送请求以前作某件事 Axios.interceptors.request.use(config => { // 设置以 form 表单的形式提交参数,若是以 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 } // 下面会说在何时存储 token if (localStorage.token) { config.headers.Authorization = 'JWT ' + localStorage.token } return config },error =>{ alert("错误的传参", 'fail') return Promise.reject(error) }) //返回状态判断(添加响应拦截器) Axios.interceptors.response.use(res =>{ //对响应数据作些事 if(!res.data.success){ alert(res.error_msg) return Promise.reject(res) } return res }, 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) }) export default { install(Vue) { Object.defineProperty(Vue.prototype, '$http', { value: Axios }) } }
main.js
import Vue from 'vue' import AxiosPlugin from 'xxx/xxx/AxiosPlugin' Vue.use(AxiosPlugin)
Login.vue
export default { name: 'Login', data() { return { username: '', password: '', } }, methods: { onLogin() { const { username, password } = this const data = { username, password } this.$http.post('url', data) .then(res => { // 登陆成功 if(res.token) { // 储存 token localStorage.token = res.token } }) .catch(error => { // 登陆失败 // 验证后端返回的错误字段,若是匹配,提示用户 // axios 配置里必需要 return Promise.reject(error.response.data) 才能拿到错误字段 if(error.xxx == 'xxx') { alert('用户名或密码错误!') } }) } } }
做者:Yi罐可乐
连接:https://www.jianshu.com/p/aeaa353da89b
來源:简书
简书著做权归做者全部,任何形式的转载都请联系做者得到受权并注明出处。
实际项目中:
require('es6-promise').polyfill(); import axios from 'axios'; import store from '../../store' import router from '../../router' export const Axios = axios.create({ timeout: 10000, }) //POST传参序列化(添加请求拦截器) // 在发送请求以前作某件事 Axios.interceptors.request.use(config => { if (localStorage.token) { config.headers.Authorization = 'Bearer ' + localStorage.token; } return config },error =>{ alert("错误的传参", 'fail') return Promise.reject(error) }) //返回状态判断(添加响应拦截器) Axios.interceptors.response.use(res =>{ //对响应数据作些事 if (res.headers.authorization) { localStorage.token = res.headers.authorization; } return res }, error => { if(error.response.status === 401 || error.response.status === 403) { // 401 说明 token 验证失败 // 能够直接跳转到登陆页面,从新登陆获取 token //location.href = '/admin/login' router.push({ path:'/login', query:{redirect:location.hostname} }) } else if (error.response.status === 500) { // 服务器错误 // do something return Promise.reject(error.response.data) } // 返回 response 里的错误信息 return Promise.reject(error.response.data) }) export default { install(Vue) { Object.defineProperty(Vue.prototype, '$axios', { value: Axios }) } }
最近写用户登陆,网上不少办法是在route的query保存上个页面的url,而后登陆后再跳转到这个页面。可是若是我跳转的页面有不少的参数也在query里,这样就很差操做了。下面我先附上用户未登陆跳转登陆页的方法。
请求我用的是axios。若是方便点,咱们能够用axios的全局配置,来拦截请求回来的数据,当请求回来的状态码不是成功的时候,跳转登陆页 ,咱们公司1001是错误的状态,这个根据本身公司来定。
跳转的登陆页后,登陆成功返回上一个页面
在登陆页中,判断若是登陆成功,写上这句话
返回上个页面,go(-2)返回上上个页面,go(0)是刷新当前页面。这样写就没有什么问题啦,可是有一种状况,登陆页是朋友分享过来的。那我以前在百度页面打开的这个连接,登陆后就跳转到了百度,这样是不行的。虽然没有直接显示登陆页的页面,可是这种状况也得考虑。
个人思路是判断上个页面的域名是否是和登陆页的域名同样,也就是说判断是否是你的项目,若是不是就跳转到首页
只须要在跳转登陆页的时候把域名传到router的query里面,你本身随便起个名字,像这样
这样在登陆页就拿到了上个页面的location.hostname了。而后在登陆页判断一下