axios对后端请求统一封装及全局调用配置

您所在的位置:网站首页 pl600使用技巧 axios对后端请求统一封装及全局调用配置

axios对后端请求统一封装及全局调用配置

2023-03-26 21:49| 来源: 网络整理| 查看: 265

 以下为个人项目笔记:

 两个文件如下:

文件【main.js】 import { createApp } from 'vue' import App from './App.vue' import router from './router' // 导入elementplus 相关依赖 import 'element-plus/dist/index.css' import * as ElementPlusIconsVue from '@element-plus/icons-vue' import ElementPlus from 'element-plus' import zhCn from 'element-plus/dist/locale/zh-cn.mjs' const app = createApp(App) // 语言配置 中文 app.use(ElementPlus, {     locale: zhCn, }) for (const [key, component] of Object.entries(ElementPlusIconsVue)) {     app.component(key, component) } // ===封装好的api在api文件夹中,如果在其他地方用,还需要一个个手动导入index.js api, 有没有办法设置全局呢,答案是有的,接下来在main.js中配置,如下: // 导入封装的api对象 import api from './api/index.js' // 将api对象设置为app的全局属性 app.config.globalProperties.$api = api app.use(router).mount('#app') 文件【 /api/index.js 】 /*全局配置:针对axios对后端请求进行统一封装,方便后续维护管理*/ import axios from "axios" const http =axios.create({     // 配置baseURL     baseURL:'http://1xx.xx.4x8:18899',     // 配置响应成功时状态码     validateStatus:function(status) {         return true      } }) // 请求拦截器,在每个请求时都会执行该方法,并把请求配置中的对象传入到该方法中 //扩展说明:在后续的非登录请求时,都需要带上鉴权 http.interceptors.request.use(function(config){     if(config.url !=='/login/'){         config.headers['Authorization']='JWT ' + window.sessionStorage.getItem('token')     }     console.log('请求拦截器:',config);     return config }); // 响应拦截器 http.interceptors.response.use(function (response) {     // 2xx 范围内的状态码都会触发该函数。     // 对响应数据做点什么     console.log('响应数据:',response);     // if(response.status === 301){     //     // 在此处对项目中接口调用失败,做统一处理,后续一一介绍并操作     // }     return response;   })

export default{     // 登录接口     login(params){         // 以下接口地址地址会与上面的baseURL自动拼接         return http.post('/login/',params)     },     // 获取项目数据     getPros(){         return http.get('/projects/',{             headers:{             'Authorization':'JWT ' + window.sessionStorage.getItem('token')             }         })     } }

原文地址:https://www.cnblogs.com/suhongzhen/p/17248308.html



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3