Creating an HTTP Configuration Module
First, create an http.js file to store the server configuration and request interceptors.
import axios from "axios";
const apiInstance = axios.create({
baseURL: 'https://your-api-domain.com',
timeout: 15000
});
apiInstance.interceptors.request.use((config) => {
const storedToken = localStorage.getItem('authToken');
if (storedToken) {
config.headers['Authorization'] = `Bearer ${storedToken}`;
}
return config;
});
export default apiInstance;
The baseURL property specifies your server's base address. The timeout option sets the maximum wait time for requests in miliseconds. The request interceptor runs before each API call is sent, allowing you to inject authentication tokens dynamically.
Storing Tokens
After a successful login, the server returns a token typically formatted as Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.... Save this token to localStorage:
localStorage.setItem('authToken', response.data.token);
Some backend services omit the Bearer prefix in their tokens. In such cases, include it manually in the interceptor by prepending Bearer to the token value, ensuring you include the trailing space.
Centralizing API Endpoints
Create an api.js file to manage all your endpoints in one place. This approach reduces duplication across components and simplifies maintenance when endpoint URLs change.
import apiClient from './http';
export const userLogin = (credentials) => apiClient.post('/auth/login', credentials);
export const fetchUserProfile = (userId) => apiClient.get(`/users/${userId}`);
export const updateUserSettings = (settings) => apiClient.put('/users/settings', settings);
export const removeAccount = (userId) => apiClient.delete(`/users/${userId}`);
To call these endpoints from components, import the specific function and pass parameters as needed:
import { userLogin } from '@/api';
async function handleLogin(credentials) {
try {
const response = await userLogin(credentials);
console.log(response.data);
} catch (error) {
console.error('Login failed:', error);
}
}
Using an interceptor to attach authorization headers keeps your components clean. Each component simply invokes the exported function without worrying about authentication configuration. When the endpoint structure changes, you update only the api.js file rather than modifying every component that makes HTTP requests.