当前位置:   article > 正文

vue+ axios+token 封装axios 封装接口url,带token请求,token失效刷新

vue axios 外链页面带token
一、封装axios
 
  1. import axios from 'axios'
  2. import qs from "qs"
  3. const TIME_OUT_MS = 60 * 1000 // 默认请求超时时间
  4. //axios.defaults.baseURL = 'http://localhost:8080';
  5. // http request 拦截器
  6. axios.interceptors.request.use(
  7. config => {
  8. if ($cookies.get("access_token")) { // 判断是否存在token,如果存在的话,则每个http header都加上token
  9. config.headers.Authorization ='Bearer '+ $cookies.get("access_token");
  10. }
  11. return config;
  12. },
  13. err => {
  14. return Promise.reject(err);
  15. });
  16. // http response 拦截器
  17. axios.interceptors.response.use(
  18. response => {
  19. return response;
  20. },
  21. error => {
  22. console.log("response error :"+error);
  23. if (error.response) {
  24. switch (error.response.status) {
  25. case 401:
  26. console.log("token 过期");
  27. var config = error.config;
  28. refresh(config);
  29. return;
  30. }
  31. }
  32. return Promise.reject(error) // 返回接口返回的错误信息
  33. });
  34. /*
  35. *刷新token
  36. */
  37. function refresh(config){
  38. var refreshToken = $cookies.get("refresh_token");
  39. var grant_type = "refresh_token";
  40. axios({
  41. method: 'post',
  42. url: '/oauth/token',
  43. data: handleParams({"grant_type":grant_type,"refresh_token":refreshToken}),
  44. timeout: TIME_OUT_MS,
  45. headers: {}
  46. }).then(
  47. (result) => {
  48. if(result.data.access_token){ //重新保存token
  49. $cookies.set("access_token",result.data.access_token);
  50. $cookies.set("refresh_token",result.data.refresh_token);
  51. //需要重新执行
  52. axios(config);
  53. }else{
  54. //this.$events.emit('goto', 'login');
  55. window.location.reload();
  56. }
  57. }
  58. ).catch((error) => {
  59. //this.$events.emit('goto','login');
  60. window.location.reload();
  61. });
  62. }
  63. /*
  64. * @param response 返回数据列表
  65. */
  66. function handleResults (response) {
  67. var result = {
  68. success: false,
  69. message: '',
  70. status: [],
  71. errorCode: '',
  72. data: {}
  73. }
  74. if (response.status == '200') {
  75. result.status = response.status;
  76. result.data = response.data;
  77. result.success = true;
  78. }
  79. return result
  80. }
  81. // function handleUrl (url) {
  82. // //url = BASE_URL + url
  83. // url =root +url;
  84. // // BASE_URL是接口的ip前缀,比如http:10.100.1.1:8989/
  85. // return url
  86. // }
  87. /*
  88. * @param data 参数列表
  89. * @return
  90. */
  91. function handleParams (data) {
  92. return qs.stringify(data);
  93. }
  94. export default {
  95. /*
  96. * @param url
  97. * @param data
  98. * @param response 请求成功时的回调函数
  99. * @param exception 异常的回调函数
  100. */
  101. post (url, data, response, exception) {
  102. axios({
  103. method: 'post',
  104. //url: handleUrl(url),
  105. url: url,
  106. data: handleParams(data),
  107. timeout: TIME_OUT_MS,
  108. headers: {
  109. //'Content-Type': 'application/json; charset=UTF-8'
  110. }
  111. }).then(
  112. (result) => {
  113. response(handleResults(result))
  114. }
  115. ).catch(
  116. (error) => {
  117. if (exception) {
  118. exception(error)
  119. } else {
  120. console.log(error)
  121. }
  122. }
  123. )
  124. },
  125. /*
  126. * get 请求
  127. * @param url
  128. * @param response 请求成功时的回调函数
  129. * @param exception 异常的回调函数
  130. */
  131. get (url,data, response, exception) {
  132. axios({
  133. method: 'get',
  134. url: url,
  135. params:data,
  136. timeout: TIME_OUT_MS,
  137. headers: {
  138. 'Content-Type': 'application/json; charset=UTF-8'
  139. }
  140. }).then(
  141. (result) => {
  142. response(handleResults(result))
  143. }
  144. ).catch(
  145. (error) => {
  146. console.log("error"+response);
  147. if (exception) {
  148. exception(error)
  149. } else {
  150. console.log(error)
  151. }
  152. }
  153. )
  154. }
  155. }

  

 
 
二、配置axios 跨域,以及请求baseUrl
1.config-->index.js
  1. 'use strict'
  2. // Template version: 1.3.1
  3. // see http://vuejs-templates.github.io/webpack for documentation.
  4. const path = require('path')
  5. //引入跨域配置
  6. var proxyConfig = require('./proxyConfig')
  7. module.exports = {
  8. dev: {
  9. // Paths
  10. assetsSubDirectory: 'static',
  11. assetsPublicPath: '/',
  12. //proxyTable: {}, //默认跨域配置为空
  13. proxyTable: proxyConfig.proxy,
  14. // Various Dev Server settings
  15. host: 'localhost', // can be overwritten by process.env.HOST
  16. port: 8886, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
  17. autoOpenBrowser: false,
  18. errorOverlay: true,
  19. notifyOnErrors: true,
  20. poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
  21. /**
  22. * Source Maps
  23. */
  24. // https://webpack.js.org/configuration/devtool/#development
  25. devtool: 'cheap-module-eval-source-map',
  26. // If you have problems debugging vue-files in devtools,
  27. // set this to false - it *may* help
  28. // https://vue-loader.vuejs.org/en/options.html#cachebusting
  29. cacheBusting: true,
  30. cssSourceMap: true
  31. },
  32. build: {
  33. // Template for index.html
  34. index: path.resolve(__dirname, '../dist/index.html'),
  35. // Paths
  36. assetsRoot: path.resolve(__dirname, '../dist'),
  37. assetsSubDirectory: 'static',
  38. // 项目名字改变时这里需要变化 原先为assetsPublicPath: '.'
  39. assetsPublicPath: './',
  40. /**
  41. * Source Maps
  42. */
  43. productionSourceMap: true,
  44. // https://webpack.js.org/configuration/devtool/#production
  45. devtool: '#source-map',
  46. // Gzip off by default as many popular static hosts such as
  47. // Surge or Netlify already gzip all static assets for you.
  48. // Before setting to `true`, make sure to:
  49. // npm install --save-dev compression-webpack-plugin
  50. productionGzip: false,
  51. productionGzipExtensions: ['js', 'css'],
  52. // Run the build command with an extra argument to
  53. // View the bundle analyzer report after build finishes:
  54. // `npm run build --report`
  55. // Set to `true` or `false` to always turn it on or off
  56. bundleAnalyzerReport: process.env.npm_config_report
  57. }
  58. }

  

 
2.config目录下创建一个文件 proxyConfig.js文件
  1. module.exports={
  2. proxy:{
  3. '/':{ //将localhost:8081 映射为 /apis
  4. target:'http://localhost:8080',//接口地址
  5. changeOrigin: true,// 如果接口跨域,需要进行这个参数配置
  6. secure:false, //如果接口是HTTPS接口,需要设置成true
  7. pathRewrite:{
  8. '^/':''
  9. }
  10. }
  11. }
  12. }

  

 
三、封装API 请求Url  port.js
 
  1. export default {
  2. oauth: {
  3. login: '/oauth/token', // 登录
  4. logout: '/oauth/logout' // // 退出
  5. },
  6. user: {
  7. addUser: '/user/add',
  8. updateUser: '/user/update',
  9. getUser:'/user/', //+ Id
  10. exists:'/exists/', // +id
  11. enable:'/enable/', // +id
  12. disable:'/disable/', // +id
  13. delete:'/delete/', //+id
  14. password:'/password ',
  15. query:'/query'
  16. }
  17. }

  

 
 
四、main.js 引入
import http from './plugins/http.js'
import ports from './plugins/ports'
Vue.prototype.http = http
Vue.prototype.ports = ports

 

 
五、使用
login.vue中使用
  1. login() {
  2. this.http.post(this.ports.oauth.login,{username:this.userId,
  3. password:this.password,grant_type:'password'}, res => {
  4. if (res.success) {
  5. // 返回正确的处理
  6. 页面跳转
  7. this.$events.emit('goto', 'edit');
  8. } else {
  9. // 返回错误的处理
  10. //alert("等待处理");
  11. }
  12. },err =>{
  13. //console.log("正在处理"+err.response.status);
  14. if(err.response.status=='400'){
  15. //显示用户名或密码错误
  16. this.$refs.username.focus();
  17. this.$refs.hint.click();
  18. }
  19. })
  20. }

  

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

转载于:https://www.cnblogs.com/Actexpler-S/p/10915299.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/715562
推荐阅读
相关标签
  

闽ICP备14008679号