I try standard fech data from db, but i have 401 problem, in postman work fine but when i try in react problem start.
Order.jsx file (REACT)
import { userRequest } from "../../requestMethods";
import { useEffect, useState } from "react";
const [orders, setOrders] = useState([]);
useEffect(() => {
const getOrders= async () => {
try {
const res = await userRequest.get("orders");
setOrders(res.data);
} catch {}
};
getOrders();
}, []);
console.log(orders);`
requestMethods.js (REACT)
import axios from "axios";
const BASE_URL = "http://localhost:5000/api/";
const user = JSON.parse(localStorage.getItem("persist:root"))?.user;
const currentUser = user && JSON.parse(user).currentUser;
const TOKEN = currentUser?.accessToken;
console.log(TOKEN);
export const publicRequest = axios.create({
baseURL: BASE_URL,
});
export const userRequest = axios.create({
baseURL: BASE_URL,
header: { token: `Bearer ${TOKEN}` },
});
order.js (node)
const Order = require("../models/Order");
const {
verifyToken,
verifyTokenAndAuthorization,
verifyTokenAndAdmin,
} = require("./verifyToken");
const router = require("express").Router();
router.get("/", verifyTokenAndAdmin, async (req, res) => {
try {
const orders = await Order.find();
res.status(200).json(orders);
} catch (err) {
res.status(500).json(err);
}
});
When i login and console.log(TOKEN) is undefined but when i refresh page i see token.
2
Answers
header
should beheaders
inuserRequest
:When you login, localStorage.getItem("persist:root") is no value. When you logined, localStorage.getItem("persist:root") has value.
and, This should be headers: