🏗️ Create an Axios Instance
ts
import axios from 'axios';
const apiClient = axios.create({
baseURL: 'https://api.example.com', // ✅ replace with your backend
timeout: 1000,
});
🔒 Set Global (Default) Headers
Use these when the same header (e.g., Authorization
) is needed for every request.
ts
apiClient.defaults.headers.common['Authorization'] = 'Bearer YOUR_TOKEN';
apiClient.defaults.headers.post['Content-Type'] = 'application/json';
These will be included with every request from apiClient
.
🎯 Set Temporary (Per-Request) Headers
Use these when you want to override or add headers for one specific call.
ts
apiClient.get('/some-path', {
headers: {
'Custom-Header': 'customValue'
}
});
📤 Upload File with multipart/form-data
+ Temporary Header
ts
const formData = new FormData();
formData.append('file', selectedFile); // ✅ selectedFile: File
apiClient.post('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data', // 🧠 Axios sets this automatically, but explicit is okay
},
});
📎 If You Need to Add Auth Temporarily Too:
ts
apiClient.post('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer TEMP_TOKEN',
},
});