JAVASCRIPT
Making Authenticated API Requests with Bearer Tokens
Learn to securely send authenticated API requests by including a Bearer token in the Authorization header using JavaScript's fetch API or Axios.
const accessToken = 'YOUR_JWT_OR_OAUTH_TOKEN_HERE'; // Get this from localStorage, session, or Redux store
// Using Fetch API
async function fetchAuthenticatedData(url) {
try {
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`
}
});
if (!response.ok) {
if (response.status === 401) {
console.error('Unauthorized: Token might be invalid or expired.');
// Redirect to login or refresh token
}
throw new Error(`HTTP error! Status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Failed to fetch authenticated data:', error);
throw error; // Re-throw for further handling
}
}
// Example Usage with Fetch API
// (async () => {
// try {
// const userProfile = await fetchAuthenticatedData('https://api.example.com/user/profile');
// console.log('User Profile:', userProfile);
// } catch (error) {
// console.error('Error fetching user profile.');
// }
// })();
// Using Axios (if installed)
// import axios from 'axios';
/*
async function axiosAuthenticatedData(url) {
try {
const response = await axios.get(url, {
headers: {
'Authorization': `Bearer ${accessToken}`
}
});
return response.data;
} catch (error) {
if (error.response && error.response.status === 401) {
console.error('Unauthorized: Token might be invalid or expired.');
// Redirect to login or refresh token
}
console.error('Failed to fetch authenticated data with Axios:', error);
throw error;
}
}
// Example Usage with Axios
// (async () => {
// try {
// const orders = await axiosAuthenticatedData('https://api.example.com/user/orders');
// console.log('User Orders:', orders);
// } catch (error) {
// console.error('Error fetching user orders.');
// }
// })();
*/
How it works: This snippet demonstrates how to make authenticated API requests by including a 'Bearer' token in the `Authorization` HTTP header. This is a standard method for securing access to resources, commonly used with JWT (JSON Web Tokens) or OAuth 2.0. The code shows implementation with both the native `fetch` API and comments on how to achieve the same with Axios, ensuring proper header configuration and basic error handling for unauthorized responses (e.g., 401 status).