Issues with req.params not getting invoked in Express.js

After hours of contemplation, I'm still struggling to figure out the issue at hand.

Let's start with how I defined a route:

var home = require('./routes/home');
var app = express();

app.use('/home/:client', home);

The code in my home.js file is as follows:

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

router.get('/', function(req, res, next) {
    res.render('homeview', { title: 'Welcome',
                             user: username});
});

router.get('/:client', function(req, res, next) {
    var theClient = req.params.client;
    console.log(theClient)
});

module.exports = router;

Now, when I attempt to visit this URL:

Nothing seems to happen. It never reaches the second router.get and fails to log anything. Can anyone spot the issue here?

Answer №1

Check out the solution on this GitHub repository.

In your app.js file:

const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
const homeRouter = require('./home');

app.use('/home', homeRouter);

app.route('/')
    .all(function (request, response, next) {
        // Perform necessary actions
        next();
    })
    .get(function (request, response, next) {
        response.send('OK GET - Hello Stack Overflow');
        next();
    });

app.listen(port, function (error) {
    if (error) {
        console.error(error.message);
    } else {
        console.info('Server up and running. Listening on port ' + port);
    }
})

In your home.js file:

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

const router = (function (router) {

    // Define the home page route
    router.get('/', function (req, res) {
        res.send('home route - homepage');
    });
    // Define the about route
    router.get('/:client', function (req, res) {
        res.send(req.params.client);
    });

    return homeRouter;
})(homeRouter);

module.exports = router;

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

What is the best way to transfer a variable from a Jade template file to a JavaScript file?

I'm completely new to Node.js and I'm struggling to understand a few things. How can I pass a variable from a Jade template file to a JavaScript file? In my server.js file, I have this line of code: res.render("aws.jade", {data : JSON.stringify ...

Error message: Express Handlebars encountered an error due to the absence of the specified file or directory

I am currently working on sending styled emails using tools such as sendgrid, nodemailer-handlebars1, and express-handlerbar@6. The folder structure related to sending emails can be found here: Below is the function used to send emails: const nodemailer = ...

What is the best way to combine two tables (documents) and retrieve only the unmatched data using mongoose(express, nodejs)?

How do I combine and retrieve unmatched data from two tables in my database using MeanJS? I need help with writing the routes and functions for joining these tables. $scope.offers = [{ id: "1", storeid: "986745", couponname: "heal ...

"Encountered an error: User.findAll function cannot be found

Here is the content of my user.js file: var sequelize = require('sequelize'); var bcrypt = require('bcrypt'); module.exports = function(sequelize, DataTypes) { const User = sequelize.define('users', { user_id: { ...

NestJs backend returning empty response to ReactJs frontend communication

My ReactJs frontend (localhost) is calling a NestJs backend: fetch("http://myappherokuapp.com/user/login", { method: "POST", mode: 'no-cors', headers: { 'Content-Type': 'appli ...

When sending an HTTP POST request to a Nodejs service with an uploaded file, the request fails after 8-15 seconds on Firefox and 25 seconds on Chrome

My web app is built on Angular 7. I am facing an issue while trying to send larger files to a Node.js service. Smaller files, around 3mb, are being sent successfully but when attempting to send bigger files like 20mb, the request gets cut off. In Chrome, I ...

Having trouble integrating Socket.io with Express.js?

I'm currently attempting to connect socket.io with express.js: var socket = require('./socket_chat/socket.js'); var express = require('express'), app = module.exports.app = express(); var io = require('socket.io&apo ...

Encountered a hiccup when trying to launch a duplicated Node.js project on my

Hello, unfortunately I am encountering yet another issue after cloning a project from GitHub onto my PC. When running the project, an error is displayed. Does anyone have a solution for this problem? The error message reads: "C:\Program Files (x86)&bs ...

What is the best way to monitor the status of the mongoose connection in Node

Is there a way to continuously monitor the status of the mongoose package connection string after starting an instance, similar to when running 'npm start'? I attempted the following approach: setInterval(function(){ if(mongoose.connection.re ...

Implementing basic authentication with React and Node.js

I'm currently utilizing the fetch API to send requests from a ReactJS frontend to a Node.js backend with Basic Authorization using the following code... React fetch(baseUrl, { method: 'get', headers: { Accept: 'application/json ...

The newly created header in Node.js (res.header) is not showing up in Chrome browser

Recently, I've started learning JavaScript, Express, and NodeJS. I'm facing an issue while attempting to create a new header containing a token upon user login (as demonstrated in the login POST router below) // Login POST Router router.post(&ap ...

What is the process for implementing parallel test execution in Jenkins using Node.js?

Looking for advice on setting up Jenkins to run tests in parallel with my Node.js app. Currently using grunt test (grunt) along with mocha, chai, and sinon for testing. ...

Express Js EJS Layouts encountered an issue: No default engine was specified and no file extension was included

Hey there! I'm currently experimenting with implementing Express EJS Layouts in my application. However, as soon as I try to include app.use(expressEjsLayouts), an error is being thrown. The application functions perfectly fine without it, but I reall ...

Employing mongoDB within Express routes

Currently, I am diving into the world of node/express, and mongodb. The concept of pooling connections has me a bit perplexed. In my current setup, I have database connections at the router level so that each route contains its own connection. var express ...

Leveraging the sofa API within a minimalist Express server configuration

Hey there. I've set up a very basic express graphql server. I'm looking to utilize sofa-api to add REST functionality. I'm facing two issues: When accessing /api/hello, it should display "Hello World!", but currently it shows as null. ...

Setting up Browser Sync, EJS, Gulp, and Node for a seamless workflow

I am currently working in a Node environment and using gulp for SASS, EJS for templates. I'm also trying to incorporate Browser Sync into my setup but running into some configuration issues with my gulp file. When I run 'node server.js', my ...

What's the deal with Angular query parameters and parentheses?

My Angular application has a routing structure that includes a query parameter. Here is an example: const routes: Routes = [{ path: '', component: DefaultComponent }, { path: ':uname', component: ProductDisplayComponent }]; Whe ...

The data seems to have disappeared from the HTTP requests in my Express and Mongoose project

I'm currently working on some files for a recipe app project. One of the files is recipe.js, where I have defined the Mongoose Schema for recipes and comments. The code snippet from the file looks like this: const express = require('express&apos ...

What are the steps to incorporate basic audio playback in a Node.js application?

I am in the process of creating a straightforward Node.js chat application utilizing socket.io and express. I want to incorporate the functionality to play a brief audio file upon clicking a button. Below is the relevant setup: var app = require('expr ...

Enter a socket.IO chat room upon accessing an Express route

Encountering difficulty when attempting to connect to a socket.IO room while accessing a specific route in my Express application. The current setup is as follows: app.js var express = require('express'); var app = express(); var http = requir ...