Projekt

Obecné

Profil

Stáhnout (1.2 KB) Statistiky
| Větev: | Tag: | Revize:
1 8c45ccb0 hrubyjar
import axiosLib from 'axios';
2
import Router from 'next/router';
3
import { StatusCodes } from 'http-status-codes';
4
import { getToken } from './login';
5 9bfa1e39 Jaroslav Hrubý
import { useContext } from 'react';
6
import { LoggedUserContext } from '../contexts/LoggedUserContext';
7 8c45ccb0 hrubyjar
8
export const axios = axiosLib.create({
9
    baseURL: 'https://localhost:7241',
10
    timeout: 60000,
11
});
12
13
// Add a request interceptor
14
axios.interceptors.request.use(async function (config) {
15
    const token = await getToken();
16
    if (token && config?.headers) {
17
        config.headers.Authorization = 'Bearer ' + token;
18
    }
19
    return config;
20
});
21
22
// Add a response interceptor
23
axios.interceptors.response.use(
24
    (response) => response,
25
    async function (error) {
26
        const status = error?.response?.status;
27
        if (status === StatusCodes.UNAUTHORIZED) {
28
            console.log('Unauthorized, redirecting...');
29 9bfa1e39 Jaroslav Hrubý
            localStorage.clear();
30 8c45ccb0 hrubyjar
            if (Router.pathname !== '/') {
31
                await Router.replace({
32
                    pathname: '/',
33
                });
34
            }
35
        } else if (status === StatusCodes.FORBIDDEN) {
36
            console.log('Forbidden:', error?.response?.config?.url);
37
        }
38
39
        throw status;
40
    }
41
);