Encountering a problem while moving the endpoint's location in Express.js

My journey to learn about REST API and session-based Authentication in express.js took an unexpected turn when I encountered a fascinating error while trying to relocate the endpoints.

Upon moving the endpoints, I decided to send a request to the /me endpoint, only to be met with an error. The code initially looked like this:

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

After rearranging, the code resulted in the following snippet:

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

However, this change led to an error involving ObjectId casting as shown below:

/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

The logic behind this error remains elusive to me currently. Here is the rest of the related code snippets:

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



Answer №1

Utilizing pattern matching, when /me is encountered, it will be directed to the route /:userId. Express prioritizes routes in the order they are defined, hence the importance of order. It is recommended to place the pattern matching as the final route, making /:userId the last specified route.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Challenge with Sequelize Many-to-Many Query

Currently, I am facing an issue with connecting to an existing MySQL database using Sequelize in Node. The database consists of a products table, a categories table, and a categories_products table. My goal is to fetch products, where each product includes ...

What is the best way to add extra plugins to a library that has already been imported through JSPM?

After successfully importing a 3D rendering library with JSPM, I encountered an issue while trying to import the Orbit Controls plugin for Three.js import THREE from 'three.js/build/three'; import OrbitControls from 'three.js/examples/js/ ...

jsGrid is failing to load within a Vue application that is utilizing static data

Struggling to implement jsGrid for a basic table with header sorting in my Javascript and Vue application. Having trouble loading the sample code with various components spread across different files. Here are the relevant parts: HTML (symbol-container is ...

Tabulator: the process of loading an extensive amount of data requires a significant amount of time

Currently, I am encountering an issue with loading data using a tabulator on my webpage. There are 38 tables that need to be populated, each containing approximately 2000 rows of data. The problem lies in the fact that it is taking an excessive amount of t ...

Using Inline Styling to Showcase a Background Image in a REACTJS Component

import React from 'react'; import Slick from 'react-slick'; import style from './Slider.module.css'; import {Link} from 'react-router-dom'; const SliderTemplates = (props) => { let template = null; const ...

React Application not reflecting recent modifications made to class

My current project involves creating a transparent navigation bar that changes its background and text color as the user scrolls. Utilizing TailwindCSS for styling in my React application, I have successfully implemented the functionality. // src/componen ...

Create a new chart using completely unique information

I am currently working on implementing the example found at http://bl.ocks.org/mbostock/1093130. The goal is to have the "update" function redraw the graph with a completely different dataset each time a button on the DOM is pressed. I have made some modif ...

Tips for modifying hover effects using jQuerystylesheet changes

I attempted running the following code snippet var buttonElement = $('<button>Button</button>'); $('body').append(buttonElement); buttonElement.hover().css('background-color', 'red'); Unfortunately, the ...

What steps should I take to fix an error in my code?

My current objective is to write a program that generates a square with dimensions of 200 pixels by 200 pixels. The square should be colored using specific RGB values: red (red value of 255), green (green value of 255), blue (blue value of 255), and magent ...

Upon reloading the page, the Vue getter may sometimes retrieve an undefined value

My blog contains various posts. Clicking on a preview will direct you to the post page. Within the post page, I utilize a getter function to display the correct post (using the find method to return object.name which matches the object in the array). cons ...

Learn the process of assigning a value to a dynamically created textbox using JavaScript in code behind

To create a textbox in the code behind, I use the following method: TextBox txt = new TextBox(); txt.ID = "txtRef" + count + dr["DataField"].ToString(); div.Controls.Add(txt); I have been attempting to set the value for this textbox within a jQuery funct ...

Implementing a click event on a selection option – tips and tricks

When I want to select an option, I can use the following script: Javascript $("#practice-area optgroup option").click(function(){ // insert your function here }); HTML <select name="practice-area" id="practice-area"> <option value="0">S ...

Ways to have Express display a randomly selected question from my personal JSON file

I have set up a personal server to enhance my backend coding skills. Currently, it is in its initial phase. I have developed a basic express application where I can import and display a JSON file. However, I am facing a challenge with automatically loading ...

Mocha fails to adhere to timeout or done callback during the execution of CasperJS tests

Trying to address a challenge using casperjs and mocha, I am attempting to verify if an element's text value on a page updates within a timeframe of 5-10 seconds. The approach involves extracting the value, storing it in an array, waiting for 500ms, a ...

Execute a native MongoDB query using the Java MongoDB driver

Is there a way to perform CRUD operations with Java using methods such as updateOne(), updateMany(), or deleteMany(), without the need to import new classes like Updates or create nested Document objects when using operators like $set or $unset? I would ...

Steps to customize Button Color and Label in a specific cell within a Material UI Table

I've implemented the Material Table to display my data, and it seems like this: In my code, I have a declared state as follows: const [sharedOrdersList, setShareOrdersList] = useState([]) When the User clicks the Share button, I push the Order Id in ...

How come my post isn't being saved to the page after I refresh it?

Utilizing Javascript, NodeJS, MongoDB, Express Within my application, a user is expected to enter text in an input field and upon clicking the submit button, the text should appear on the page. I have succeeded in posting text to the page; however, after ...

Assess the HTML containing v-html injection

Is there a way to inject raw HTML using Vue, especially when the HTML contains Vue markup that needs to be evaluated? Consider the following example where HTML is rendered from a variable: <p v-html="markup"></p> { computed: { m ...

Clicking the ASP button does not trigger the onclick event when a web user control is included on the webpage

I have been working on a web form application that I developed using the visual studio template. The template includes a content placeholder that gets replaced by the content of each accessed page. One particular page, which contains server controls like t ...

Is it feasible to have multiple versions of React coexisting in a monorepo?

I have a monorepo set up with npm workspaces: ├─ lib │ └─ Foo └─ src ├─ App └─ Web I am looking to upgrade the Web package to React 18 while keeping App on React 17 My current dependencies are as follows: ├─ lib │ └ ...