Programming & Development / April 18, 2025

Set Headers in Axios Instance & Per-Request (Including Multipart Files)

axios set header axios multipart form data axios instance temporary headers

🏗️ 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',
  },
});



Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex