You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
house/fount/vm/http.js.vm

52 lines
1.9 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

// 引入 axios 库用于发起 HTTP 请求
import axios from 'axios'
// 引入静态路由模块,用于在请求失败或 token 失效时跳转到登录页
import router from '@/router/router-static'
// 引入本地存储工具模块,用于操作 Token 等信息
import storage from '@/utils/storage'
// 创建一个 axios 实例,配置基础参数
const http = axios.create({
timeout: 1000 * 86400, // 超时时间设置为一天(单位:毫秒)
withCredentials: true, // 允许携带 cookies
baseURL: '/${schemaname}', // 请求的基础路径,使用 schemaname 动态替换模块名
headers: { // 默认请求头
'Content-Type': 'application/json; charset=utf-8' // 指定内容类型为 JSON
}
})
// 请求拦截器:在每次请求发出前做一些处理
http.interceptors.request.use(config => {
// 在请求头中添加 Token 字段,从 storage 中获取当前用户的 Token
config.headers['Token'] = storage.get('Token') // 请求头带上token
// 返回修改后的请求配置对象
return config
}, error => {
// 请求错误时拦截并返回 Promise reject
return Promise.reject(error)
})
// 响应拦截器:在每次响应到达前做一些处理
http.interceptors.response.use(response => {
// 如果响应数据中有 code 且值为 401表示 Token 失效
if (response.data && response.data.code === 401) {
// 清除登录信息(该方法未启用,可根据需要实现)
// clearLoginInfo()
// 跳转到登录页面
router.push({ name: 'login' })
}
// 返回响应结果
return response
}, error => {
// 响应出错时拦截并返回 Promise reject
return Promise.reject(error)
})
// 导出自定义的 axios 实例,供其他组件或模块调用
export default http