[web教学] vue中axios的二次封装——vue 封装axios详细步调

[复制链接]
查看1078 | 回复0 | 2023-8-23 11:42:14 | 显示全部楼层 |阅读模式 来自 中国北京
一、为什么要封装axios

       api统一管理,不管接口有多少,全部的接口都可以非常清晰,轻易维护。
      通常我们的项目会越做越大,页面也会越来越多,如果页面非常的少,直接用axios也没有什么大的影响,那页面组件多了起来,上百个接口呢,这个时间后端改了接口,多加了一个参数什么的呢?那就只有找到谁人页面,进去修改,整个过程很繁琐,不易于项目标维护和迭代。
      这个时间如果我们统一的区管理接口,必要修改某一个接口的时间直接在api里修改对应的请求,是不是很方便呢?由于我们用的最多的还是get post请求,我们就可以针对封装。
  二、怎么封装 axios

   1. 拿到项目和后端接口,首先要设置全局署理;
2. 接着全局封装axios和request.js;
3. 过滤axios请求方式,控制路径,参数的格式,http.js;
4. 正式封装api.js;
5. 页面调用;
   三、详细步调

(一)vue项目标前期设置

   1. 终端输入
  1. npm i axios -S
复制代码
   2. 在项目中 main.js 文件中输入
  1. import axios from "axios";
复制代码
(二)设置config文件中的署理地址 

    修改项目中config目次下的 index.js文件。【也可能是vue.config.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. module.exports = {
  6.   dev: {
  7.     // Paths
  8.     assetsSubDirectory: 'static',
  9.     assetsPublicPath: '/',
  10.     proxyTable: {
  11.       '/': {
  12.         target: 'http://localhost:8080',
  13.         changeOrigin: true,
  14.         pathRewrite: {
  15.           '^/': ''
  16.         }
  17.       },
  18.       '/ws/*': {
  19.         target: 'ws://127.0.0.1:8080',
  20.         ws: true
  21.       }
  22.     },
  23.     // Various Dev Server settings
  24.     host: 'localhost', // can be overwritten by process.env.HOST
  25.     port: 8082, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
  26.     autoOpenBrowser: false,
  27.     errorOverlay: true,
  28.     notifyOnErrors: true,
  29.     poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
  30.     // Use Eslint Loader?
  31.     // If true, your code will be linted during bundling and
  32.     // linting errors and warnings will be shown in the console.
  33.     useEslint: true,
  34.     // If true, eslint errors and warnings will also be shown in the error overlay
  35.     // in the browser.
  36.     showEslintErrorsInOverlay: false,
  37.     /**
  38.      * Source Maps
  39.      */
  40.     // https://webpack.js.org/configuration/devtool/#development
  41.     devtool: 'cheap-module-eval-source-map',
  42.     // If you have problems debugging vue-files in devtools,
  43.     // set this to false - it *may* help
  44.     // https://vue-loader.vuejs.org/en/options.html#cachebusting
  45.     cacheBusting: true,
  46.     cssSourceMap: true
  47.   },
  48.   build: {
  49.     // Template for index.html
  50.     index: path.resolve(__dirname, '../dist/index.html'),
  51.     // Paths
  52.     assetsRoot: path.resolve(__dirname, '../dist'),
  53.     assetsSubDirectory: 'static',
  54.     assetsPublicPath: '/',
  55.     /**
  56.      * Source Maps
  57.      */
  58.     productionSourceMap: true,
  59.     // https://webpack.js.org/configuration/devtool/#production
  60.     devtool: '#source-map',
  61.     // Gzip off by default as many popular static hosts such as
  62.     // Surge or Netlify already gzip all static assets for you.
  63.     // Before setting to `true`, make sure to:
  64.     // npm install --save-dev compression-webpack-plugin
  65.     productionGzip: false,
  66.     productionGzipExtensions: ['js', 'css'],
  67.     // Run the build command with an extra argument to
  68.     // View the bundle analyzer report after build finishes:
  69.     // `npm run build --report`
  70.     // Set to `true` or `false` to always turn it on or off
  71.     bundleAnalyzerReport: process.env.npm_config_report
  72.   }
  73. }
复制代码
 (三)封装axios实例 —— request.js

  1. /****   request.js   ****/
  2. // 导入axios
  3. import axios from 'axios'
  4. // 使用element-ui Message做消息提醒
  5. import { Message} from 'element-ui';
  6. //1. 创建新的axios实例,
  7. const service = axios.create({
  8.   // 公共接口--这里注意后面会讲
  9.   baseURL: process.env.BASE_API,
  10.   // 超时时间 单位是ms,这里设置了3s的超时时间
  11.   timeout: 3 * 1000
  12. })
  13. // 2.请求拦截器
  14. service.interceptors.request.use(config => {
  15.   //发请求前做的一些处理,数据转化,配置请求头,设置token,设置loading等,根据需求去添加
  16.   config.data = JSON.stringify(config.data); //数据转化,也可以使用qs转换
  17.   config.headers = {
  18.     'Content-Type':'application/json' //配置请求头
  19.   }
  20.   //如有需要:注意使用token的时候需要引入cookie方法或者用本地localStorage等方法,推荐js-cookie
  21.   //const token = getCookie('名称');//这里取token之前,你肯定需要先拿到token,存一下
  22.   //if(token){
  23.   //config.params = {'token':token} //如果要求携带在参数中
  24.   //config.headers.token= token; //如果要求携带在请求头中
  25.   //}
  26.   return config
  27. }, error => {
  28.   Promise.reject(error)
  29. })
  30. // 3.响应拦截器
  31. service.interceptors.response.use(response => {
  32.   //接收到响应数据并成功后的一些共有的处理,关闭loading等
  33.   return response
  34. }, error => {
  35.   /***** 接收到异常响应的处理开始 *****/
  36.   if (error && error.response) {
  37.     // 1.公共错误处理
  38.     // 2.根据响应码具体处理
  39.     switch (error.response.status) {
  40.       case 400:
  41.         error.message = '错误请求'
  42.         break;
  43.       case 401:
  44.         error.message = '未授权,请重新登录'
  45.         break;
  46.       case 403:
  47.         error.message = '拒绝访问'
  48.         break;
  49.       case 404:
  50.         error.message = '请求错误,未找到该资源'
  51.         window.location.href = "/NotFound"
  52.         break;
  53.       case 405:
  54.         error.message = '请求方法未允许'
  55.         break;
  56.       case 408:
  57.         error.message = '请求超时'
  58.         break;
  59.       case 500:
  60.         error.message = '服务器端出错'
  61.         break;
  62.       case 501:
  63.         error.message = '网络未实现'
  64.         break;
  65.       case 502:
  66.         error.message = '网络错误'
  67.         break;
  68.       case 503:
  69.         error.message = '服务不可用'
  70.         break;
  71.       case 504:
  72.         error.message = '网络超时'
  73.         break;
  74.       case 505:
  75.         error.message = 'http版本不支持该请求'
  76.         break;
  77.       default:
  78.         error.message = `连接错误${error.response.status}`
  79.     }
  80.   } else {
  81.     // 超时处理
  82.     if (JSON.stringify(error).includes('timeout')) {
  83.       Message.error('服务器响应超时,请刷新当前页')
  84.     }
  85.     error.message = '连接服务器失败'
  86.   }
  87.   Message.error(error.message)
  88.   /***** 处理结束 *****/
  89.   //如果不需要错误处理,以上的处理过程都可省略
  90.   return Promise.resolve(error.response)
  91. })
  92. //4.导入文件
  93. export default service
复制代码
四、封装请求——http.js 

  1. /****   http.js   ****/
  2. // 导入封装好的axios实例
  3. import request from './request'
  4. const http ={
  5.   /**
  6.    * methods: 请求
  7.    * @param url 请求地址
  8.    * @param params 请求参数
  9.    */
  10.   get(url,params){
  11.     const config = {
  12.       method: 'get',
  13.       url:url
  14.     }
  15.     if(params) config.params = params
  16.     return request(config)
  17.   },
  18.   post(url,params){
  19.     const config = {
  20.       method: 'post',
  21.       url:url
  22.     }
  23.     if(params) config.data = params
  24.     return request(config)
  25.   },
  26.   put(url,params){
  27.     const config = {
  28.       method: 'put',
  29.       url:url
  30.     }
  31.     if(params) config.params = params
  32.     return request(config)
  33.   },
  34.   delete(url,params){
  35.     const config = {
  36.       method: 'delete',
  37.       url:url
  38.     }
  39.     if(params) config.params = params
  40.     return request(config)
  41.   }
  42. }
  43. //导出
  44. export default http
复制代码
五、正式封装API,用于发送请求——api.js 

  1. import request from "@/utils/request.js";
  2. import qs from "qs";
  3. const baseUrl = '/api/jwt/auth'
  4. //登录
  5. export function authCodeLogin(params) {
  6.   return request({
  7.     url: baseUrl + "/authCodeLogin/" + params.code,
  8.     method: "get",
  9.   });
  10. }
  11. //退出
  12. export function authLogout(params) {
  13.   return request({
  14.     url: baseUrl + "/logout",
  15.     method: "get",
  16.   });
  17. }
  18. //获取用户数据
  19. export function getUserInfo(params) {
  20.   return request({
  21.     url: baseUrl + "/getUserInfo",
  22.     method: "get",
  23.     params:qs.stringfy(params)
  24.   });
  25. }
  26. //其实,也不一定就是params,也可以是 query 还有 data 的呀!
  27. //params是添加到url的请求字符串中的,用于get请求。会将参数加到 url后面。所以,传递的都是字符串。无法传递参数中含有json格式的数据
  28. //而data是添加到请求体(body)中的, 用于post请求。添加到请求体(body)中,json 格式也是可以的。
复制代码

 六、如安在vue文件中调用

    用到哪个api 就调用哪个接口
  1. import { authCodeLogin  } from '@/api/api.js'
  2.    getModellogin(code){
  3.       let params = {
  4.         code: code,
  5.       }
  6.       authCodeLogin(params).then(res=>{
  7.         if (res.code === 200) {
  8.           localStorage.clear()
  9.           // 菜单
  10.           this.$store.dispatch('saveMenu', [])
  11.           // this.getFloorMenu()
  12.           // this.getmenu()
  13.           this.$router.push('/')
  14.         }else{
  15.           console.log('error');
  16.         }
  17.       })
  18.     },
复制代码
   其实还挺简单的!~

   纪录一下,方便忘记的时间拿起来用。

来源:https://blog.csdn.net/Vivien_CC/article/details/127507545
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则