Projekt

Obecné

Profil

Stáhnout (1.24 KB) Statistiky
| Větev: | Tag: | Revize:
1
import axiosLib from 'axios';
2
import Router from 'next/router';
3
import { StatusCodes } from 'http-status-codes';
4
import { getToken } from './login';
5
import { useContext } from 'react';
6
import { LoggedUserContext } from '../contexts/LoggedUserContext';
7
import { getApiBasePath } from '../constants';
8

    
9
export const axios = axiosLib.create({
10
    baseURL: getApiBasePath(),
11
    timeout: 60000,
12
});
13

    
14
// Add a request interceptor
15
axios.interceptors.request.use(async function (config) {
16
    const token = await getToken();
17
    if (token && config?.headers) {
18
        config.headers.Authorization = 'Bearer ' + token;
19
    }
20
    return config;
21
});
22

    
23
// Add a response interceptor
24
axios.interceptors.response.use(
25
    (response) => response,
26
    async function (error) {
27
        const status = error?.response?.status;
28
        if (status === StatusCodes.UNAUTHORIZED) {
29
            console.log('Unauthorized, redirecting...');
30
            localStorage.clear();
31
            if (Router.pathname !== '/') {
32
                await Router.replace({
33
                    pathname: '/',
34
                });
35
            }
36
        } else if (status === StatusCodes.FORBIDDEN) {
37
            console.log('Forbidden:', error?.response?.config?.url);
38
        }
39

    
40
        throw status;
41
    }
42
);
(2-2/6)