JAVASCRIPT
Making a POST Request with Bearer Token Authentication using Axios
Discover how to send data to an API using a POST request with the Axios library, including how to attach a Bearer Token for secure authentication.
import axios from 'axios';
async function postDataWithAuth(url, data, token) {
try {
const response = await axios.post(url, data, {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
});
return response.data;
} catch (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.error("API Error Response:", error.response.data);
console.error("Status:", error.response.status);
console.error("Headers:", error.response.headers);
} else if (error.request) {
// The request was made but no response was received
console.error("No API response received:", error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.error("Error setting up request:", error.message);
}
throw error;
}
}
// Example usage:
// const myData = { name: 'Test User', email: '[email protected]' };
// const myToken = 'your_bearer_token_here';
// postDataWithAuth('https://api.example.com/users', myData, myToken)
// .then(response => console.log('Data posted successfully:', response))
// .catch(error => console.error('Failed to post data:', error));
How it works: This snippet illustrates how to perform a POST request using Axios, a popular promise-based HTTP client for JavaScript. It correctly sets the `Content-Type` header for JSON data and includes an `Authorization` header with a Bearer Token for secure API authentication. Robust error handling for various Axios error types (response, request, setup) is also included, making it suitable for sending data to protected API endpoints.