-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaxios-interceptor.js
52 lines (47 loc) · 1.33 KB
/
axios-interceptor.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import axios from 'axios';
// Create an Axios instance
const api = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com',
});
// Add a request interceptor
api.interceptors.request.use(
(config) => {
// Modify the request config before sending it
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`; // Attach token to headers
}
console.log('Request:', config);
return config;
},
(error) => {
// Handle request error
return Promise.reject(error);
}
);
// Add a response interceptor
api.interceptors.response.use(
(response) => {
// Handle the response data before passing it to the calling code
console.log('Response:', response);
return response;
},
(error) => {
// Handle errors globally (e.g., log out the user if 401 Unauthorized)
if (error.response && error.response.status === 401) {
console.error('Unauthorized, logging out...');
// Logic to log out the user or redirect to login
}
return Promise.reject(error);
}
);
// Using the axios instance to make requests
const fetchPosts = async () => {
try {
const response = await api.get('/posts');
console.log('Fetched posts:', response.data);
} catch (error) {
console.error('Error fetching posts:', error);
}
};
fetchPosts();