Last active
May 17, 2024 00:52
-
-
Save walosha/b4654b7e627574a97fe62cb545d6d340 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
You can use Axios interceptors to automatically append the bearer token from local storage to all outgoing requests. Here's how you can set it up: | |
```javascript | |
import axios from 'axios'; | |
// Create an instance of axios | |
const axiosInstance = axios.create(); | |
// Add a request interceptor | |
axiosInstance.interceptors.request.use( | |
config => { | |
// Get the token from local storage | |
const token = localStorage.getItem('token'); | |
// If a token exists, add it to the request headers | |
if (token) { | |
config.headers.Authorization = `Bearer ${token}`; | |
} | |
return config; | |
}, | |
error => { | |
// Do something with request error | |
return Promise.reject(error); | |
} | |
); | |
export default axiosInstance; | |
``` | |
With this setup: | |
- The interceptor intercepts all outgoing requests before they are sent. | |
- It retrieves the token from local storage. | |
- If a token exists, it adds it to the request headers with the format `"Bearer <token>"`. | |
- If there's an error with the request, it rejects the promise with the error. | |
Now, whenever you make a request using `axiosInstance`, the bearer token will be automatically added to the request headers if it exists in local storage. For example: | |
```javascript | |
import axiosInstance from './axiosInstance'; | |
axiosInstance.get('https://api.example.com/data') | |
.then(response => { | |
console.log(response.data); | |
}) | |
.catch(error => { | |
console.error('Error:', error); | |
}); | |
``` | |
Make sure to replace `'token'` with the key under which your token is stored in local storage. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment