не могу понять почему ошибка в get запросе с сервера.
в хроме выводит в консоле - xhr.
js:247 GET
localhost:2000/api/user/auth 404 (Not Found)
причём из БД подтягивается инфа.
Ошибка в части авторизации, я сделал админ аккаунт в Postmane и на эти аккаунты я могу попасть с клиента и делать операции с БД, но загребать новый ак не могу, так же присутствует сбой в прогрузке элемента - Админ панель.
Работа с 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 jwt_decode from "jwt-decode";
export const registration = async (email, password) => {
const { data } = await $host.post("api/user/registration", {
email,
password,
role: "ADMIN",
});
localStorage.setItem("token", data.token);
return jwt_decode(data.token);
};
export const login = async (email, password) => {
const { data } = await $host.post("api/user/login", { email, password });
localStorage.setItem("token", data.token);
return jwt_decode(data.token);
};
export const check = async () => {
const { data } = await $authHost.get("/api/user/auth");
localStorage.setItem("token", data.token);
return jwt_decode(data.token);
};
главный компонент
import React, { useContext, useEffect, useState } from "react";
import { BrowserRouter } from "react-router-dom";
import AppRouter from "./components/AppRouter";
import NavBar from "./components/NavBar";
import { observer } from "mobx-react-lite";
import { Context } from "./index";
import { check } from "./http/userAPI";
import { Spinner } from "react-bootstrap";
const App = observer(() => {
const { user } = useContext(Context);
const [loading, setLoading] = useState(true);
useEffect(() => {
check()
.then((data) => {
user.setUser(true);
user.setIsAuth(true);
})
.finally(() => setLoading(false));
}, [user]);
if (loading) {
return <Spinner animation={"grow"} />;
}
return (
<BrowserRouter>
<NavBar />
<AppRouter />
</BrowserRouter>
);
});
export default App;
NavBar(выход)
const NavBar = observer(() => {
const { user } = useContext(Context);
const navigate = useNavigate();
const logOut = () => {
user.setUser({});
user.setIsAuth(false);
};
return (
<Navbar bg="dark" variant="dark">
<Container>
<NavLink style={{ color: "white" }} to={SHOP_ROUTE}>
Купить Цветы
</NavLink>
{user.isAuth ? (
<Nav className="ml-auto" style={{ color: "white" }}>
<Button
variant={"outline-light"}
onClick={() => navigate(ADMIN_ROUTE)}
>
Админ панель
</Button>
<Button
variant={"outline-light"}
onClick={() => logOut()}
className="ml-2"
>
Выйти
</Button>
</Nav>
) : (
<Nav className="ml-auto" style={{ color: "white" }}>
<Button
variant={"outline-light"}
onClick={() => navigate(LOGIN_ROUTE)}
>
Авторизация
</Button>
</Nav>
)}
</Container>
</Navbar>
);
});
export default NavBar;
сама авторизация
import React, { useContext, useState } from "react";
import { Container, Form } from "react-bootstrap";
import Card from "react-bootstrap/Card";
import Button from "react-bootstrap/Button";
import Row from "react-bootstrap/Row";
import { NavLink, useLocation, useNavigate } from "react-router-dom";
import { LOGIN_ROUTE, REGISTRATION_ROUTE, SHOP_ROUTE } from "../utils/consts";
import { login, registration } from "../http/userAPI";
import { observer } from "mobx-react-lite";
import { Context } from "../index";
const Auth = observer(() => {
const { user } = useContext(Context);
const location = useLocation();
const navigate = useNavigate();
const isLogin = location.pathname === LOGIN_ROUTE;
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const click = async () => {
try {
let data;
if (isLogin) {
data = await login(email, password);
} else {
data = await registration(email, password);
}
alert(data);
user.setUser(user);
user.setIsAuth(true);
navigate(SHOP_ROUTE);
} catch (e) {
alert(e.response.message.data);
}
};
return (
<Container
className="d-flex justify-content-center align-items-center"
style={{ height: window.innerHeight - 54 }}
>
<Card style={{ width: 600 }} className="p-5">
<h2 className="m-auto">{isLogin ? "Авторизация" : "Регистрация"}</h2>
<Form className="d-flex flex-column">
<Form.Control
className="mt-3"
placeholder="Введите ваш email..."
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<Form.Control
className="mt-3"
placeholder="Введите ваш пароль..."
value={password}
onChange={(e) => setPassword(e.target.value)}
type="password"
/>
<Row className="d-flex justify-content-between mt-3 pl-3 pr-3">
{isLogin ? (
<div>
Нет аккаунта?{" "}
<NavLink to={REGISTRATION_ROUTE}>Зарегистрируйся!</NavLink>
</div>
) : (
<div>
Есть аккаунт? <NavLink to={LOGIN_ROUTE}>Войдите!</NavLink>
</div>
)}
<Button variant={"outline-success"} onClick={click}>
{isLogin ? "Войти" : "Регистрация"}
</Button>
</Row>
</Form>
</Card>
</Container>
);
});
export default Auth;