7
7
700Hp2021-10-06 12:56:23
JavaScript
700Hp, 2021-10-06 12:56:23

After checking for the presence of an authorization token, a 401 error for unauthorized people falls. How to remove the error?

This problem
615d70b6b6e47944128852.png
does not affect the work in any way, but I think that any mistakes need to be corrected.

The principle is as follows:
Axios work

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)
}


main component.
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 that exits
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


Function that is nested in the authorization form
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)
        }
    }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question