I was following a tutorial to create a user authentication – a user dashboard page is hidden and appears if the user is logged in. It works perfectly fine at the /
directory but not if I change the /
directory to /dashboard
, even if I update all instances of "/"
to "/dashboard"
.
Here’s my Axios code for authenticating if the user is logged in; the problem arises in /api/private
, where I get a 404 error GET http://localhost:3000/api/private 404 (Not Found)
ONLY when the directory for the user’s dashboard is NOT at "/"
.
const fetchPrivateDate = async () => {
const config = {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${localStorage.getItem("authToken")}`,
},
};
try {
const { data } = await axios.get("/api/private", config);
setPrivateData(data.data);
} catch (error) {
localStorage.removeItem("authToken");
console.log(error);
setError("Error");
}
};
fetchPrivateDate();
}, []);
Here is the server node.js code:
app.get("/dashboard", (req, res, next) => {
res.send("Operational");
});
app.use("/api/auth", require("./routes/auth"));
app.use("/api/private", require("./routes/private"));
I believe the /auth path works; login and signup work completely fine, it’s just that once the user logs in the dashboard it catches an error because it can’t find api/private
.
Here is routes/private
aka api/private
:
const express = require("express");
const router = express.Router();
const { getPrivateRoute } = require("../controllers/private");
const { protect } = require("../middleware/auth");
router.route("/dashboard").get(protect, getPrivateRoute);
module.exports = router;
I looked at plenty of other posts, such as this one: Method Post with Axios giving Error 404. ReactJS but none of the changes, such as updating the axios.get
to include localhost:3000
works at all. For reference, this is the tutorial I followed: https://www.youtube.com/watch?v=YocRq-KesCM&list=LL. I’ve tried several solutions online and nothing seems to work. Any help would be greatly appreciated.