Projekt

Obecné

Profil

Stáhnout (1.07 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
6
export const axios = axiosLib.create({
7
    baseURL: 'https://localhost:7241',
8
    timeout: 60000,
9
});
10
11
// Add a request interceptor
12
axios.interceptors.request.use(async function (config) {
13
    const token = await getToken();
14
    if (token && config?.headers) {
15
        config.headers.Authorization = 'Bearer ' + token;
16
    }
17
    return config;
18
});
19
20
// Add a response interceptor
21
axios.interceptors.response.use(
22
    (response) => response,
23
    async function (error) {
24
        const status = error?.response?.status;
25
        if (status === StatusCodes.UNAUTHORIZED) {
26
            console.log('Unauthorized, redirecting...');
27
28
            if (Router.pathname !== '/') {
29
                await Router.replace({
30
                    pathname: '/',
31
                });
32
            }
33
        } else if (status === StatusCodes.FORBIDDEN) {
34
            console.log('Forbidden:', error?.response?.config?.url);
35
        }
36
37
        throw status;
38
    }
39
);