Better bracket logic
This commit is contained in:
@@ -1,42 +1,48 @@
|
||||
// frontend/src/services/api.js
|
||||
|
||||
import axios from 'axios';
|
||||
|
||||
const getBackendHost = () => {
|
||||
const host = window.location.hostname || 'localhost';
|
||||
return host;
|
||||
};
|
||||
|
||||
// Updated to include /api prefix
|
||||
export const API_BASE = `${window.location.protocol}//${getBackendHost()}:8000/api`;
|
||||
export const WS_URL = `${window.location.protocol === 'https:' ? 'wss:' : 'ws:'}//${getBackendHost()}:8000/ws`;
|
||||
const port = '8000';
|
||||
|
||||
const api = axios.create({
|
||||
baseURL: API_BASE,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
export const API_BASE = `${window.location.protocol}//${getBackendHost()}:${port}/api`;
|
||||
export const WS_URL = `${window.location.protocol === 'https:' ? 'wss:' : 'ws:'}//${getBackendHost()}:${port}/api/ws`;
|
||||
|
||||
// Request Interceptor for Auth
|
||||
api.interceptors.request.use((config) => {
|
||||
const token = localStorage.getItem('volleyToken');
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
return config;
|
||||
});
|
||||
|
||||
// Response Interceptor for Errors
|
||||
api.interceptors.response.use(
|
||||
(response) => response.data,
|
||||
(error) => {
|
||||
if (error.response?.status === 401) {
|
||||
localStorage.removeItem('volleyToken');
|
||||
window.location.href = '/login';
|
||||
export const getToken = () => localStorage.getItem('volleyToken');
|
||||
|
||||
const api = {
|
||||
request: async (method, url, data = null, isFormData = false) => {
|
||||
const headers = {};
|
||||
const token = getToken();
|
||||
if (token) headers['Authorization'] = `Bearer ${token}`;
|
||||
if (!isFormData) headers['Content-Type'] = 'application/json';
|
||||
|
||||
const opts = { method, headers };
|
||||
if (data) opts.body = isFormData ? data : JSON.stringify(data);
|
||||
|
||||
// Ensure clean URL concatenation
|
||||
const baseUrl = API_BASE.endsWith('/') ? API_BASE.slice(0, -1) : API_BASE;
|
||||
const endpoint = url.startsWith('/') ? url : `/${url}`;
|
||||
|
||||
const res = await fetch(`${baseUrl}${endpoint}`, opts);
|
||||
if (!res.ok) {
|
||||
if (res.status === 401) {
|
||||
localStorage.removeItem('volleyToken');
|
||||
window.location.href = '/login';
|
||||
}
|
||||
throw await res.json();
|
||||
}
|
||||
return Promise.reject(error.response?.data || error.message);
|
||||
}
|
||||
);
|
||||
return res.json();
|
||||
},
|
||||
get: (url) => api.request('GET', url),
|
||||
post: (url, data) => api.request('POST', url, data),
|
||||
postForm: (url, data) => api.request('POST', url, data, true),
|
||||
put: (url, data) => api.request('PUT', url, data),
|
||||
patch: (url, data) => api.request('PATCH', url, data),
|
||||
delete: (url) => api.request('DELETE', url)
|
||||
};
|
||||
|
||||
export default api;
|
||||
Reference in New Issue
Block a user