Headers in the fetch() API are key-value pairs sent along with HTTP requests or responses to provide metadata like content format, authorization, etc.
🔹 Example of Headers in fetch():
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json', // Tells server the format of body
'Authorization': 'Bearer your-token-here' // Used for auth
},
body: JSON.stringify({ name: 'Teekam' })
});
🔹 What is Content-Type?
Content-Type tells the server what format the request body is in so it knows how to parse it.
🔸 Common Content-Type Values:
'application/json'→ Sending JSON data'application/x-www-form-urlencoded'→ Form data in URL-encoded format'multipart/form-data'→ For file uploads (used withFormData)
🔹 Example: JSON Request
fetch('/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ email: 'test@test.com', password: '123456' })
});
✅ This tells the server: “I’m sending JSON, please parse it accordingly.”