![]()
Forgetting to Set Headers in an API Request
When making API requests, headers are crucial for passing metadata like authentication tokens, content types, and other information the server requires. Forgetting to set headers can lead to authentication errors, CORS issues, or unexpected server behavior.
Common Mistake Example (Missing Headers):
fetch('https://api.example.com/data') // ❌ No headers set
.then(response => response.json())
.then(data => console.log(data));
Possible Errors:
- 401 Unauthorized if the API requires an Authorization token.
- 400 Bad Request if the server expects specific content types.
- CORS errors if custom headers are missing when accessing resources from different origins.
✅ Correct Way (Setting Headers):
fetch('https://api.example.com/data', {
method: 'GET',
headers: {
'Content-Type': 'application/json', // ✅ Essential for JSON APIs
'Authorization': 'Bearer your_token_here' // ✅ For authenticated APIs
}
})
.then(response => response.json())
.then(data => console.log(data));
Why This Works:
- The
Content-Typeheader tells the server the type of data being sent. - The
Authorizationheader is often required for APIs that use token-based authentication.
Common Mistake: Missing Headers in POST Requests
fetch('https://api.example.com/data', {
method: 'POST',
body: JSON.stringify({ name: 'John Doe' }) // ❌ Missing Content-Type header
})
.then(response => response.json())
.then(data => console.log(data));
Fix:
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json' // ✅ Required for JSON payloads
},
body: JSON.stringify({ name: 'John Doe' })
})
.then(response => response.json())
.then(data => console.log(data));
✅ Headers for APIs Requiring Token Authentication
const token = 'your_api_token_here';
fetch('https://api.example.com/secure-data', {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'Accept': 'application/json'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Mistake: Incorrect Header Format
fetch('https://api.example.com/data', {
headers: 'Authorization: Bearer token' // ❌ Incorrect format
});
Fix:
fetch('https://api.example.com/data', {
headers: {
'Authorization': 'Bearer token' // ✅ Correct format
}
});
Key Takeaways:
- Always set the
Content-Typeheader when sending data in requests (especially POST/PUT). - Use the
Authorizationheader for APIs that require authentication. - For APIs with custom headers (like
X-API-Key), make sure to include them. - Check the API documentation to confirm which headers are required.
- Use
try-catchblocks for better error handling withfetch.
