Exploring request parameters within an Express router

I'm currently facing an issue with accessing request parameters in my express router.

In my server.js file, I have the following setup:

app.use('/user/:id/profile', require('./routes/profile'));

Within my ./routes/profile.js file, this code is present:

router.get('/', (req, res) => {
    console.log(req.params.id);
}

Despite this setup, the console log displays undefined. I am fairly new to express and suspect that I might be overlooking something fundamental about how routing functions. Could someone kindly provide some guidance on this?

Below is the complete content of my server.js:

const express = require('express');
const app = express();
app.use(express.json());

app.use('/user/:id/profile', require('./routes/profile'));

app.listen(5000, () => console.log('Listening'));

Below is the full content of my profile.js:

const express = require('express');
const router = express.Router();

router.get('/', (req, res) => {
  console.log(req.params.id);
  res.status(200).send('In profile route');
});

module.exports = router;

Answer №1

When it comes to URL parameters, routers do not expose them. Here are a couple of approaches you can take:

  1. You could extract the user id from req.originalUrl, although this method is not recommended. The value of req.originalUrl will remain unchanged by the router's mount point, displaying something like /user/112/profile regardless of the actual route visited.
  2. An alternative option is to utilize middleware to make the id accessible (which is the preferred method). Your updated route statement would look similar to the following:

(This change allows you to access req.userId in your profile.js)

app.use('/user/:id/profile', function(req, res, next) {
    req.userId = req.params.id;
    next();
}, require('./routes/profile'));
  1. If desired, you could modify the mount point from /user/:id/profile to simply /user and adjust your router to listen on /:id/profile instead (although this approach is not highly recommended).

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

Ensuring the accuracy of URLs using JavaScript

I am developing a form with an input field for entering a URL and a submit button. I want to incorporate JavaScript validation to show an alert box when a correct URL is entered. Is it achievable using JavaScript? If so, can you please guide me on how to i ...

Execute the script using ajax

Is it possible to execute JavaScript within an AJAX request? I attempted to include some JavaScript code in the PHP file that was called by an AJAX command. The purpose of this script was to modify an HTML attribute on the parent page. However, it did not ...

Tips for expanding frisby.js by adding new "expect" functionalities?

Looking to enhance the Frisby.js module with custom expect methods without altering the source code. These extensions are tailored for my REST API to streamline common tests into a single method. An issue arises as the Frisby.js module exports its methods ...

What is the default way to toggle content in rows using Material UI?

Currently, I am utilizing Muitables and have a query regarding how to set the expanded rows to be displayed by default, similar to the illustration below: Upon initial page load, it is preferred for the content in that row to automatically expand (arrow d ...

Retrieve the place_id associated with the address components

Having trouble obtaining the place_id of address_components using Google place autocomplete? The JSON data only includes long_name, short_name, and types. Take a look at my code snippet below: var object_location = document.getElementById('object_loc ...

Discovering the clicked button in a partial view during an onSuccess Ajax call

Within my partial view, I have implemented two buttons: Save and Preview. Both buttons are functioning as expected, with Preview enabling widget preview and Save saving data to the database. However, I am encountering two issues: I am unable to determine ...

Is it possible to generate a "pop-up" window upon clicking on the register button?

As a backend programmer, I'm looking to create a popup window that appears in front of the current window when users click "register", eliminating the need for redirection to another page. I believe you understand the concept. How can I achieve this? ...

What is the method to determine the duration of a video using the FileReader function to access the video file?

My current challenge involves uploading a video to a server and reading it on the client end using `readAsBinaryString()` from FileReader. However, I am facing an issue when trying to determine the duration of this video file. If I attempt to read the fi ...

Error handling within middleware does not propagate errors

Essentially, I have an async function structured like this: export default (htmlFilePath, observer, redisClient) => async (req, res, next) => { try { ...lots of logic... } catch (error) { // when I log the error here, it shows up correctly ...

Is it possible to authenticate a user in Firebase using Node.js without utilizing the client side?

Can I access Firebase client functions like signInWithEmailAndPassword in the Firebase SDK on the server side? Although SDKs are typically used for servers and clients use JavaScript, I need a non-JavaScript solution on the client side. I have set up the ...

Retrieve records with at least one connection, but display all of them

After creating this entry, it now consists of 2 tags - tag1 and tag2. { "id": "d87de1d9-b048-4867-92fb-a84dca59c87e", "name": "Test Name", "tags": [ { "id": "fa0ca8fd-eff4-4e58-8bb0-a1ef726f01d4", "name": "tag1", "organizationI ...

JavaScript Regular Expression for standardizing phone number input

I'm working with an input for a phone number in French format which can accept two different formats: 0699999999 +33699999999 There is currently no check for the length of the number. In the database table, the field is varchar 12, but shorter inp ...

Unfortunate escapement of characters discovered in variable that returns JSON image source

I am currently utilizing Google Tag Manager to incorporate the 'article' JSON markup and retrieve different variables for modifying specific sections on particular pages. Among the elements I am attempting to obtain is the image source. At prese ...

Iterate through the list of objects and display duplicates only once

var fixtures = [ { "matchday": 1, "homeTeamName": "Arsenal FC", "awayTeamName": "Leicester City FC" }, { "matchday": 1, "homeTeamName": "AFC Bournemouth", ...

What is the best way to navigate between different areas of an image using html and javascript?

I am currently in the process of learning how to develop mobile applications, and I am still in the early stages. Although this question is not directly related to mobile development, it pertains more to html/css/js. My goal is to create a simple game wh ...

Using Puppeteer to Retrieve a List of Items with Identical Selectors

Issue: I am currently working on developing an end-to-end regression test for an EmberJS solution using NodeJS/CucumberJS/Puppeteer. However, I have encountered a challenge that I need help with. Challenge: The problem lies in selecting (page.click) and ...

The size of the array within the object does not align

I've run into a roadblock while attempting to implement the tree hierarchy in D3. Initially, I believed that I had correctly structured the JSON data, but upon inspecting the object using Developer's Tool, a discrepancy caught my eye: https://i. ...

Alter the functionality of the input element that has a tag of 'multiple'

I am encountering an issue with a form that allows users to upload multiple photos. When selecting multiple files at once, everything works as expected. However, if a user wants to add images one by one, each new addition deletes the previous file due to t ...

Converting Cookies to Numeric Values in JavaScript: A Step-by-Step Guide

I'm currently developing a cookie clicker website and am encountering an issue with saving the user's score to localstorage when they click the "save" button. Here is what my code looks like: let score = 0; function addPoint() { score += 1; } ...

TypeScript error: Cannot find property 'propertyName' in the 'Function' type

I encountered an issue with the TypeScript compiler when running the following code snippet. Interestingly, the generated JavaScript on https://www.typescriptlang.org/play/ produces the desired output without any errors. The specific error message I recei ...