I try to learn REST API and session based Authenticaion in express.js. But I got really interesting error when try to relocate the endpoints.
After relocating the endpoints I send a request to /me
endpoint but I get an error. For instance;
// This code works fine
router.get("/me", sessionChecker, async (req, res, next) => {
const { userId } = req.session.payload;
const user = await UserService.findUserById(userId);
return res.json(user);
});
router.get("/:userId", sessionChecker, async (req, res, next) => {
const { userId } = req.params;
const user = await UserService.findUserById(userId);
return res.json(user);
});
to this;
// This code gives error
router.get("/:userId", sessionChecker, async (req, res, next) => {
const { userId } = req.params;
const user = await UserService.findUserById(userId);
return res.json(user);
});
router.get("/me", sessionChecker, async (req, res, next) => {
const { userId } = req.session.payload;
const user = await UserService.findUserById(userId);
return res.json(user);
});
I'am getting this error;
/Users/Desktop/projects/Curioso/backend/node_modules/mongoose/lib/query.js:4913
const castError = new CastError();
^
CastError: Cast to ObjectId failed for value "me" (type string) at path "_id" for model "User"
at model.Query.exec (/Users/Desktop/projects/Curioso/backend/node_modules/mongoose/lib/query.js:4913:21)
at model.Query.Query.then (/Users/Desktop/projects/Curioso/backend/node_modules/mongoose/lib/query.js:5012:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
messageFormat: undefined,
stringValue: '"me"',
kind: 'ObjectId',
value: 'me',
path: '_id',
reason: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer
I couldn't understand what is the problem or logic of this error. Here is the rest of the code;
index.js
const express = require("express");
const session = require("express-session");
const MongoStore = require("connect-mongo");
const mongoose = require("mongoose");
const authRouter = require("./routes/auth");
const roomsRouter = require("./routes/rooms");
const usersRouter = require("./routes/users");
var cors = require("cors");
require("dot-env");
const app = express();
mongoose
.connect(process.env.MONGODB_URL)
.then(() => {
console.log("Connected to DB");
})
.catch((error) => {
console.log(error);
});
var whitelist = ["http://localhost:3000"];
var corsOptions = {
origin: whitelist,
methods: ["POST", "PUT", "GET", "OPTIONS", "HEAD"],
credentials: true,
};
app.use(cors(corsOptions));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(
session({
secret: process.env.SESSION_SECRET_KEY,
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 1000 * 60 * 60 * 24,
secure: process.env.NODE_ENV === "production",
httpOnly: true,
},
store: MongoStore.create({
mongoUrl: process.env.MONGODB_URL,
}),
})
);
app.use("/auth", authRouter);
app.use("/rooms", roomsRouter);
app.use("/users", usersRouter);
app.listen(8000, () => {
console.log(`Example app listening on port 8000`);
});
routes/user.js
const express = require("express");
const { sessionChecker } = require("../middlewares/auth");
const router = express.Router();
const UserService = require("../services/user");
router.get("/", sessionChecker, async (req, res, next) => {
const allUsers = await UserService.getAllUsers();
return res.json(allUsers);
});
router.get("/:userId", sessionChecker, async (req, res, next) => {
const { userId } = req.params;
const user = await UserService.findUserById(userId);
return res.json(user);
});
router.get("/me", sessionChecker, async (req, res, next) => {
const { userId } = req.session.payload;
const user = await UserService.findUserById(userId);
return res.json(user);
});
module.exports = router;
middlewares/auth.js
const { HTTP_ERRORS } = require("../utils/constants");
const sessionChecker = (req, res, next) => {
const userSession = req.session.payload.userId;
if (!userSession) {
return res
.status(HTTP_ERRORS.UNAUTHORIZED.CODE)
.send(HTTP_ERRORS.UNAUTHORIZED.MESSAGE);
}
next();
};
module.exports = { sessionChecker };
CodePudding user response:
Because you are using pattern matching /me
will go to the route /:userId
. Express follows routes from first defined to last defined to find a matching route, this is why the order matters.
It is the practise to put the pattern matching as the last route so /:userId
should be the last route.