Files
nanocode/personal-blog/frontend/src/api/config.js
T
Ubuntu 32b43f85bd a
2026-07-03 16:58:28 +08:00

44 lines
1.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import axios from 'axios'
// API基础配置 - 使用绝对URL确保跨域访问
// 强制使用后端端口 8889
export const API_BASE_URL = 'http://129.211.173.87:8889/api'
const api = axios.create({
baseURL: API_BASE_URL,
headers: {
'Content-Type': 'application/json'
},
timeout: 10000,
withCredentials: true, // 允许跨域携带 Cookie(SSO 必需)
})
// 请求拦截器 - 添加Token
api.interceptors.request.use(
(config) => {
const token = localStorage.getItem('token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
},
(error) => Promise.reject(error)
)
// 响应拦截器 - 处理错误
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
localStorage.removeItem('token')
// 避免在登录页本身触发跳转导致死循环刷新
if (window.location.pathname !== '/login') {
window.location.href = '/login'
}
}
return Promise.reject(error)
}
)
export default api