vue中使用axios固定url请求前缀
作者:Agwenbi
这篇文章主要介绍了vue中使用axios固定url请求前缀的实现方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
使用axios固定url请求前缀
main.js中添加:
使用方法:
定义axios默认路径前缀或动态修改前缀
如:每个请求url前都要加一个前缀,但会根据开发环境不同而变化,那么我们可以写一个方法去引用,方便后面维护
.env.development 开发文件中写入要用的服务编码
# 微服务编码 VUE_APP_SERVICE_PREFIX = '/0201010254'
src/settings.js 新建的settings文件中引入
module.exports = { /** * 主站标题 * @type {string} */ title: '开发项目名称', /** * @type {boolean} true | false * @description Whether fix the header */ fixedHeader: false, /** * @type {string | array} 'production' | ['production', 'development'] * @description Need show err logs component. * The default is only used in the production env * If you want to also use it in dev, you can pass ['production', 'development'] */ errorLog: 'production', /** * base API */ baseApi: process.env.VUE_APP_BASE_API, /** * 服务编码 */ servicePrefix: process.env.VUE_APP_SERVICE_PREFIX, }
之后请求文件中引入
新建api/app.js 封装axios请求并引用自定义的服务编码文件
// 应用层封装接口 import request from '@/utils/request' import settings from '@/settings' // 获取配置 不需替换 export function getAppConfig(params) { return request({ url: settings.servicePrefix + '/config', method: 'get', params }) }
其中的request文件是引用自建的请求拦截文件,根据各自需求
import axios from 'axios' import store from '@/store' import { getToken, removeToken } from '@/utils/auth' const BASE_URL = process.env.VUE_APP_BASE_API // create an axios instance const service = axios.create({ // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url // withCredentials: true, // send cookies when cross-domain requests timeout: 60 * 1000 // request timeout }) // request interceptors service.interceptors.request.use( config => { // do something before request is sent // 设置baseURL config.baseURL = config.url.startsWith('/mock') ? '' : BASE_URL const token = getToken() if (!config.noAuth && token) { // let each request carry token config.headers['Authorization'] = token } if (store.state.user.info && store.state.user.info.comId) { config.headers['comId'] = store.state.user.info.comId config.headers['comCode'] = store.state.user.info.comCode config.headers['groupUserCode'] = store.state.user.info.groupUserCode config.headers['userCode'] = store.state.user.info.userCode } return config }, error => { // do something with request error return Promise.reject(error) } ) // response interceptor service.interceptors.response.use( /** * If you want to get http information such as headers or status * Please return response => response */ /** * Determine the request status by custom code * Here is just an example * You can also judge the status by HTTP Status Code */ response => { if (response.headers.newjwt) { store.dispatch('user/setToken', response.headers.newjwt) } if ((response.data.status && +response.data.status === 16) || response.status === 401) { if (response.status === 401) { return Promise.reject('没有接口权限,请联系管理员') } else { setTimeout(() => { // 清除登录状态 removeToken() window.location.href = '/' }, 1000) return Promise.reject('登录超时,请重新登录') } } if (response.config.handleResponse) { return response } else { const { head, body } = response.data // 旧数据格式分为head和body两部分,现在使用ApiResponse不会再出现这两部分,此处为兼容旧格式的临时方案 if (head && body) { // 正常返回 if (+head.code === 1) { return body } else { return Promise.reject(head.msg || '未知错误') } } else { const { status, statusText, data } = response.data if (+status === 0) { return data } else { if (response.config.handleError) { return Promise.reject(response.data) } else { return Promise.reject(statusText || '未知错误') } } } } }, error => { // 非取消请求 if (!axios.isCancel(error)) { // 401无权限判断 if (error.response && error.response.status === 401) { return Promise.reject('没有接口权限,请联系管理员') } else if (error.response && error.response.status === 531) { setTimeout(() => { // 清除登录状态 removeToken() window.location.href = '/' }, 1000) return Promise.reject('登录超时,请重新登录') } } return Promise.reject(error) } ) export default service
request.js中把token内容抽离出来方便管理
src下新建/utils/auth.js
import Cookies from 'js-cookie' const TokenKey = 'Admin-Token' export function getToken() { return Cookies.get(TokenKey) } export function setToken(token) { if (!token || token === 'null') { return } sessionStorage.setItem('jwt', token) return Cookies.set(TokenKey, token) } export function removeToken() { return Cookies.remove(TokenKey) }
最终页面使用axios
import { getAppConfig } from '@/api/app' //请求 const params = {} getAppConfig(params).then(res => { this.loading = false console.log(res) }).catch(e => { this.loading = false this.$message.error(e.toString()) })
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。