Problem with displaying requests at the endpoint on the Express Router

I'm currently delving into the world of express and experimenting with express.Router() to route to various endpoints. Despite following online tutorials diligently, I am only able to successfully send text from the root '/' endpoint and not any other endpoint. My code aligns closely with the tutorial I referenced, so I am at a loss as to what may be missing.

express.js

"use strict";
const express = require('express');
const app = express();

const resources = require('../routes/resources');
const commonExpress = require('common/lib/express');

commonExpress.setup_pre(app);
app.use('/', (req, res) => {
    res.send('<h1>Hey Socket.io</h1>');
});

app.use('/resources', resources)
//use /routes/resources to handle endpoints
//that start with '/resources'

commonExpress.setup_post(app);

module.exports = app;

resources.js

"use strict";
const express = require('express');
const router = express.Router();

router.use(function(req, res, next) {
    console.log(req.url, "@", Date.now());
    next();
});

router.route('/messages').get((req, res) => {
    res.send("hi get /resources/messages")
}).post((req, res) => {
    res.send("hi post /resources/messages");
});
router.route('/messages/:userId').get((req, res) => {
    res.send("hi get /resources/messages " + req.params.userId);
}).put((req, res) => {
    res.send("hi put /resources/messages " + req.params.userId);
})

module.exports = router;

commonExpress

const express = require('express');
const logger = require('morgan');
const utils = require('./utils');
const cookieParser = require('cookie-parser');

module.exports = {
    setup_pre: app => {
        app.use(logger('dev'));
        app.use(express.json());
        app.use(cookieParser());
        app.use('/health', (req, res) => res.status(200).send());
    },
    setup_post: app => {
        app.disable('x-powered-by');
        app.use(utils.handleMezError);
        app.use(utils.handleMongoError);
        app.use(utils.handleUnknownError);
        app.use(function (req, res, next) {
            res.status(404).send();
        })
    }
};

When I utilize the curl command, here are the responses I receive:

tk@tk-desktop:~/messenger$ curl http://localhost:4000/
<h1>Hey Socket.io</h1>tk@tk-desktop:~/messenger$ curl http://localhost:4000/resources
<h1>Hey Socket.io</h1>tk@tk-desktop:~/messenger$ curl http://localhost:4000/resources/messages
<h1>Hey Socket.io</h1>tk@tk-desktop:~/messenger$ curl http://localhost:4000/resources/messages/:userId

Answer №1

Your code here:

app.use('/', (req, res) => {
    res.send('<h1>Hey Socket.io</h1>');
});

This code snippet captures all possible URLs and responds to them without allowing other request handlers to see the incoming requests until it has processed them. The order of request handlers in Express matters as they are executed sequentially based on registration. Only the handlers registered before this specific one that grabs the inbound request can run prior to its execution, such as those within commonExpress.setup_pre(app);.

To make it more precise and exclusive, it is recommended to modify the route as follows:

app.get('/', (req, res) => {
    res.send('<h1>Hey Socket.io</h1>');
});

By making this change, the route will only respond to GET requests and will specifically match the / URL.

Here are some key points to consider:

  1. app.use() is a broad matcher for inbound URLs as it matches any path starting with the specified keyword. In contrast, app.get() is more specific and matches only exact URLs. Therefore, using app.use() for middleware tasks that do not involve sending a response is common practice. After sending a response without calling next(), the routing for that request is concluded.

  2. The sequence of registering request handlers in Express determines their execution order. Placing more lenient handlers after stricter ones ensures the latter get prioritized. In the current scenario, the overly broad handler seizes all routes, preventing subsequent handlers from running.

  3. You have the option to either convert app.use('/', ...) to app.get('/', ...) for precise matching or maintain it as a middleware function that delegates control to the next handler without responding directly.

  4. Review your usage of app.use() versus app.get() to align with the intended HTTP verb functionality. For endpoints delivering content requested by browsers, employing app.get() to signify a GET request is preferred over app.use(), which supports multiple verbs.

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

Strict routing is broken by Express adding a trailing slash to the root path

In order to define my express endpoints, I typically use app.get or app.post methods. While this approach usually works fine, I have noticed that a trailing slash gets added to the root directory when the HTML view is returned. This results in the root vi ...

The setCountry function fails to properly change the country value

My goal is to establish a default country selection in checkbox options, I have three choices: United States, United Kingdom, and Rest of the world; Here's the constant called AVAILABLE_COUNTRIES which contains the iso codes for the mentioned countrie ...

Transforming a massive JSON object into a Blob concerns directly converting it into an ArrayBuffer or Blob to prevent exceeding the maximum string length error

Situation: Within my application, I am encountering the following code: let blob = new Blob([JSON.stringify(json)], {type: "application/json"}); This code sometimes fails because the maximum string length allowed in Chrome is approximately 500M ...

Discover the final index of an array with Angular's ng-repeat functionality

I'm currently working with an Object that contains array values which I am trying to iterate over. Here's a simplified example of what I have: $scope.messages = { "1": [ { "content": "Hello" }, { "content": "How are you" }, { "conte ...

The JSON file containing API data is stored within the _next folder, making it easily accessible to anyone without the need for security measures or a login in the Next

When accessing the protected user Listing page, we utilize SSR to call the api and retrieve all user records which are then rendered. However, if one were to check the Network tab in Chrome or Firefox, a JSON file containing all user data is generated and ...

Personalizing text in HTML using JavaScript results

I have a modal dialog box function that pops up when a user clicks a button, triggered by a javascript/jquery script. The text displayed in the dialog is set up within an HTML div element that references the script function. My query is how to personalize ...

What steps are needed to configure ESLint to exclusively analyze .ts files?

I need ESLint to exclusively focus on processing .ts files and not .js files. In order to achieve that, I made a .eslintignore file and included the following lines: *.js **/*.js Nevertheless, it appears that ESLint is disregarding this file. Is there so ...

Mastering the Art of Concise Writing: Tips to

Is there a way to write more concisely, maybe even in a single line? this.xxx = smt.filter(item => item.Id === this.smtStatus.ONE); this.yyy = smt.filter(item => item.Id === this.smtStatus.TWO); this.zzz = smt.filter(item => item.Id == ...

KnockoutJS's data binding feature is failing to display any content within the table rows

My JavaScript function creates a model and applies it to an HTML document using knockoutJS. In the HTML file, I have two different ways of displaying the same data: 1- A select list (which is working fine) 2- A table (not showing the same data) I need a ...

Step-by-step guide on accessing values from a JavaScript object

I have a dictionary variable declared within a script tag on an HTML page. My goal is to retrieve the values associated with the "Roads" and "Intersections" keys, which change each time the page is refreshed. By capturing these values, I can then use JavaS ...

The functionality for the "OnChange" event in the <html:select> field does not seem to be functioning properly

My JavaScript function isn't functioning properly. I can't see any alert messages on my webpage. Can someone please assist me? Below is my HTML code function checkProjectStatus() { alert("Helloo"); var dropdownType = document.getElementById( ...

The Node.js server is outputting an HTTP status code of 404

I have recently set up a small server. Interestingly, when I attempt to perform a GET request to my server through a browser, I can see the correct data. However, when I try to make a POST request to my server using code, I receive an HTTP status 404 error ...

Why does Socket.IO seem to be registering two clients instead of just one when there is only one connection

When using my app, the user first lands on the home screen where they can select their username. They then proceed to another page and from there, navigate to the room entry page. The issue I'm facing is with a specific section of my code that update ...

How can we display the Recent Updates from our LinkedIn profile on our website using iframe or javascript?

Currently, I am in the process of developing a .NET web application for our company's website. We already maintain an active LinkedIn profile where we regularly post updates. https://i.stack.imgur.com/T2ziX.png My main query at this point is whether ...

Is it possible to achieve consistent scrollY height values across various screen sizes?

Looking to apply a class when a certain screen height is reached? Here's my approach: window.onscroll = function() {scrollPost()}; function scrollPost () { var x = window.screen.width; var i = window.scrollY; var a = i / x; animator ...

Make sure the express app is active before initiating mocha tests

I recently created an API for a Couchbase database using Express and Node.js. Interestingly, during my testing phase, some tests failed due to the server not being fully operational. After doing some research, I came across a helpful solution outlined on t ...

Issue: ENOENT - The specified file or directory, './views/s.ejs', does not exist in Node.js Express

Encountering an error when attempting to render a file from the 'views' directory in the 'routes'. The specific error message is as follows: Error: Valid Login { [Error: ENOENT: no such file or directory, open './views/s ...

Establish the designated callback URL for iOS applications within an Express framework

My current project involves an Express app that has a feature allowing users to sign in with Google using passport-google-oauth20. The callback route for this functionality is set as: https://(hosturl)/auth/google/redirect. I am currently facing an issue ...

Learn how to acquire a JWT token with Next Auth V5

I am struggling to understand how Next Auth creates a JWT token, and I'm unsure of how to retrieve it. Here is the configuration within the auth.ts file: import NextAuth from "next-auth"; import Google from "next-auth/providers/google& ...

Exploring JQuery and JavaScript for loop guide

Currently working on a small application where users are required to input information, and I am implementing text hints in the input fields. However, I have encountered an issue when using a for loop in my code. Oddly enough, the text hints display corre ...