Initial commit: 商品售卖网站
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api'
|
||||
const BASE_URL = API_BASE_URL.replace('/api', '')
|
||||
|
||||
export function getImageUrl(path: string): string {
|
||||
if (!path) return ''
|
||||
if (path.startsWith('http://') || path.startsWith('https://')) {
|
||||
return path
|
||||
}
|
||||
if (path.startsWith('/')) {
|
||||
return BASE_URL + path
|
||||
}
|
||||
return BASE_URL + '/' + path
|
||||
}
|
||||
|
||||
export function getFirstImage(images: string): string {
|
||||
if (!images) return ''
|
||||
const arr = images.split(',').map((s: string) => s.trim()).filter(Boolean)
|
||||
const first = arr[0] || ''
|
||||
return getImageUrl(first)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import axios from 'axios'
|
||||
import { ElMessage } from 'element-plus'
|
||||
|
||||
const api = axios.create({
|
||||
baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api',
|
||||
timeout: 30000,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
})
|
||||
|
||||
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.data,
|
||||
(error) => {
|
||||
const message = error.response?.data?.error || error.message || 'Request failed'
|
||||
if (error.response?.status === 401) {
|
||||
const hadToken = !!localStorage.getItem('token')
|
||||
localStorage.removeItem('token')
|
||||
localStorage.removeItem('user')
|
||||
if (hadToken) {
|
||||
window.location.href = '/login'
|
||||
}
|
||||
} else {
|
||||
ElMessage.error(message)
|
||||
}
|
||||
return Promise.reject(error)
|
||||
},
|
||||
)
|
||||
|
||||
export default api
|
||||
Reference in New Issue
Block a user