Сия проблема
На работе никак не сказывается, но считаю, любые ошибки нужно исправлять.
Принцип следующий:
Работа Axios
import axios from 'axios'
const $host = axios.create({
baseURL: process.env.REACT_APP_API_URL
})
const $authHost = axios.create({
baseURL: process.env.REACT_APP_API_URL
})
const authInterceptor = config => {
config.headers.authorization = `Bearer ${localStorage.getItem('token')}` // Добавить токен
return config
}
$authHost.interceptors.request.use(authInterceptor)
export {
$host,
$authHost
}
import {$authHost, $host} from "./index"
import jwtDecode from "jwt-decode"
export const registration = async (email, password, secondPassword) => {
const {data} = await $host.post('api/user/registration', {email, password, secondPassword})
localStorage.setItem('token', data.token)
return jwtDecode(data.token)
}
export const login = async (email, password) => {
const {data} = await $host.post('api/user/login', {email, password})
localStorage.setItem('token', data.token)
return jwtDecode(data.token)
}
export const check = async () => {
const {data} = await $authHost.get('api/user/auth')
localStorage.setItem('token', data.token)
return jwtDecode(data.token)
}
Главный компонент.
import React, {useContext, useEffect, useState} from 'react'
import {BrowserRouter} from "react-router-dom"
import AppRouter from "./components/AppRouter"
import Navbar from "./components/UI/Navbar/Navbar"
import {observer} from "mobx-react-lite"
import {Context} from "./index";
import {check} from "./http/userAPI";
const App = observer(() => {
const {user} = useContext(Context)
const [loading, setLoading] = useState(true)
useEffect(() => {
check().then(data => {
user.setIsUser(true)
user.setIsAuth(true)
}).finally(() => setLoading(false))
}, [])
return (
<BrowserRouter>
<Navbar />
<AppRouter />
</BrowserRouter>
)
})
export default App
NavBar, с помощью которого осуществляется выход
const Navbar = observer(() => {
const {user} = useContext(Context)
const logOut = () => {
user.setIsUser({})
user.setIsAuth(false)
localStorage.removeItem('token')
}
return (
// Переделать через history push
<div className={classes.nav}>
{user.isAuth ?
<div>
<Link to={LOGIN_ROUTE} className={classes.nav__link} onClick={() => logOut()}>Выйти</Link>
<Link to={HOME_ROUTE} className={classes.nav__link}>Главная</Link>
<Link to={TASK_ROUTE} className={classes.nav__link}>Задачи</Link>
</div>
:
<div>
<Link to={LOGIN_ROUTE} className={classes.nav__link}>Войти</Link>
<Link to={HOME_ROUTE} className={classes.nav__link}>Главная</Link>
</div>
}
</div>
)
})
export default Navbar
Функция, которая вложена в форму авторизации
const {user} = useContext(Context)
const isLogin = location.pathname === LOGIN_ROUTE
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [secondPassword, setSecondPassword] = useState('')
const click = async () => {
try {
let data
if (isLogin) {
data = await login(email, password)
} else {
data = await registration(email, password, secondPassword)
}
user.setIsUser(user)
user.setIsAuth(true)
history.push(TASK_ROUTE)
} catch (e) {
alert(e.response.data.message)
}
}