aboutsummaryrefslogtreecommitdiff
path: root/src/index.js
blob: d620e5d6d0003464b91529600f13c79b6add987b (plain)
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import axios from 'axios';
import { BrowserRouter } from "react-router-dom";

// For GET requests
axios.interceptors.request.use(
  config => {
    const token = localStorage.getItem("accessToken");
    if (token) config.headers.Authorization = token;
    return config;
  },
  err => new Promise((resolve) => {
    if (err.response && err.response.status === 401) {
      err.config._retry = true;

      const response = fetch("/auth/refresh", {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      })
        .then((res) => res.json())
        .then((res) => {
          if (res.accessToken && res.accessToken !== "") {
            localStorage.setItem("accessToken", res.accessToken);
            return axios(err.config);
          } else {
            window.location = "/login"
          }
        })
      resolve(response);
    } else {
      return Promise.reject(err);
    }
  })
);

// For POST requests
axios.interceptors.response.use(
  config => {
    const token = localStorage.getItem("accessToken");
    if (token) config.headers.Authorization = token;
    return config;
  },
  err => new Promise((resolve) => {
    if (err.response && err.response.status === 401 && err.config.url !== "/auth/login") {
      err.config._retry = true;

      const response = fetch("/auth/refresh", {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      })
        .then((res) => res.json())
        .then((res) => {
          if (res.accessToken && res.accessToken !== "") {
            localStorage.setItem("accessToken", res.accessToken);
            return axios(err.config);
          } else {
            window.location = "/login"
          }
        })
      resolve(response);
    } else {
      return Promise.reject(err);
    }
  })
);

axios.defaults.baseURL = "/";

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
);