Having trouble with expressJS routing, basic problem not getting resolved

After organizing all my route code into separate files, I've noticed that my route resolution is inconsistent. Here's a basic example -

Code in my app.js file

const express = require('express');
const app = express();

var dataLoader = require('./routes/dataLoader');
app.all( '/api/load', dataLoader);

Content of my dataLoader.js file

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

router.get('/api/load', (req, res) => {
    res.send('Hello Loader...');
});

router.get('/api/load/bob', (req, res) => {
   res.send('Hello Loader - Bob...');
});

router.get('/api/load/jim', (req, res) => {
   res.send('Hello Loader - Jim...');
});

module.exports = router;

While /api/load works fine, trying to access /api/load/jim or /api/load/bob results in:

Cannot GET /api/load/jim (or Cannot GET /api/load/bob, respectively) 

I used app.all() instead of app.use() to resolve the main path "/api/load" because I encountered issues with it initially. Although using all seemed to solve that problem, now I am unsure.

"engines": { "node": "^8.9.1" }, "dependencies": { "bluebird": "^3.5.1", "body-parser": "^1.15.1", "express": "^4.13.4", "mongoose": "4.9.8" } Any suggestions?

Answer №1

When you follow these steps:

app.all('/api/load', dataLoader);

Then, within the dataLoader router, you set up routes like this:

router.get('/api/load', (req, res) => {
    res.send('Hello Loader...');
});

You might unintentionally be creating a route for api/load/api/load, which is probably not your intention. The paths are cumulative.

The correct approach is to have the app.use() statement with the common prefix for your entire router and then define relative paths on the router itself. Furthermore, it is advisable to use app.use() instead of app.all() for a router.

In this scenario, you should modify the dataLoader router as follows:

// Entire router is configured at /api/loader
const router = require('express').Router();

router.get('/', (req, res) => {
    res.send('Hello Loader...');
});

router.get('/bob', (req, res) => {
   res.send('Hello Loader - Bob...');
});

router.get('/jim', (req, res) => {
   res.send('Hello Loader - Jim...');
});

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

Guide on swapping OAuth2 authorization codes for access tokens sent by a client (Ember) through Express

Currently, I am utilizing ember-simple-auth and torii within my Ember application to manage OAuth2 authentication with Facebook and Google on the client side. As a result of this process, I obtain an authorization code. My objective is to transmit this co ...

Is it possible for the user/website to access the express res.locals variables?

In the process of developing a Node app with Express and Passport, I have incorporated middleware in my main server.js file as shown below: // Function to protect urls function isProtected(req, res, next) { if (req.isAuthenticated()) { // User ...

pg-promise received an error due to an incorrect parameter being passed in for options

I have been working on transitioning my files from utilizing the pg package to the pg-promise package. Initially, everything was functioning correctly with the original pg solution I had in place. However, upon switching to pg-promise and referencing the d ...

NodeJS controller function to generate and send a response

I'm facing an issue with my controller method where I am unable to send a response to the user, even though the value is displaying in the console. Below is my code snippet: const hubHome = (req,res) => { const hubId = req.params.hubId; fetch ...

Utilizing Folders in Views on Your Express Application

Within my views folder, I have a pug template named fixed-assets.pug located in views/administration/assets/ The main template default.pug, which the fixed-assets.pug extends from, is situated in the root views directory. Upon attempting to render the fi ...

Is there a way for me to access the user's gender and birthday following their login using their Google account details?

I have successfully implemented a Google sign-in button in my Angular application following the example provided in Display the Sign In With Google button: <div id="g_id_onload" class="mt-3" data-client_id="XXXXXXXXXXXX-XX ...

Exploring the variation between server port and websocket port in a Node.js chat system

I'm currently working on developing a multi-room chat application in node.js that uses socket.io and express. I've been having some confusion regarding the differences between the server port and the websocket port. As far as I know, the server p ...

Switching from HTTP to HTTPS with Express and Heroku

Despite Heroku's suggestion to use NPM packages, I've had no luck finding one that successfully forces SSL for express apps. The only solution that seems to work is the following, but it angers Google. Question: Can anyone provide a reliable met ...

Heroku deployment causes Node.js application to crash

My Node.js app works perfectly fine locally, but once deployed on Heroku, it fails to run. I have already deployed it from my Github repository. If anyone could try deploying the app from my repo and identify the cause of the issue, that would be greatly ...

Utilize Relative Paths when working with node.js and express

Can someone help me troubleshoot an issue with running my node server on localhost? Currently, I am only able to run it using a static path: app.get("/", function(req, res){ res.sendFile("/Users/name/Documents/_privat/dungeon/index.html"); }); Obviou ...

The error occurred in async JavaScript parallel code because the task is not recognized as a function

I am attempting to upload an image and update the image URL in the database collection using the code provided below. Controller.prototype.handle = function (req, res, next) { var id = req.params.id, controller = req.params.controller, optio ...

Performing Numerous Validations in Mysql Using ExpressJS and NodeJS

Hello, I am just starting out with NodeJS and currently working on an ExpressJS API to use with angular2. I am facing a problem where I need to perform database checks (MySQL) before inserting data and handle any errors that may occur. However, my code se ...

How to read a config file using Node.js in an HTML file

In my configuration file, I have stored all the necessary settings. app: { root: 'rooturl' } I also have an HTML file that serves as a template. My goal is to access the config file from within the HTML file. <img src='rooturl&apos ...

Building a Node.js authentication system for secure logins

Just diving into node.js and trying to create a user login system, but encountering an error when registering a new user: MongoDB Connected (node:12592) UnhandledPromiseRejectionWarning: TypeError: user is not a constructor at User.findOne.then.user ...

Is your current Angular 2 project in need of data retrieval from a SQL server?

Currently, I am facing a challenge with my Angular 2 application as I am unable to connect and send queries to an existing SQL server. It has come to my attention that in order to achieve this, I need to create a RESTful API using 'express.js'. I ...

accessing past sign-ins with passport.js and express-sessions

I need some assistance with displaying a user's login history on the front-end of my webpage. I am using Express and storing sessions in mongoStore as shown below: app.use(session({ secret: process.env.SECRET, key: process.env.KEY, resave: fals ...

Express.js not redirecting to Angular route, app not starting

I have the following setup in my node.js app.js: app.use('/', routes); app.get('some_api', routes.someApi); app.use(function (req, res) { res.sendFile(path.join(__dirname, 'public', 'index.html')); }); Additio ...

Is it possible to determine the file size of an http-streamed file?

In my node app, I am sending a large file via express using a stream since the size of the file is substantial. When the receiving node app downloads the file, I want to be able to monitor the progress of the download. I came across a discussion on Stack ...

Error encountered when attempting to utilize a variable within an EJS template document

I seem to be encountering some difficulties while attempting to get an EJS template file to recognize a variable that holds the rows from an SQLite3 table query in a related .js file. Whenever I try to access that route by launching the server, I receive a ...

Despite the status being 500, Chai is successfully navigating the test cases

I'm currently conducting test cases for my API using Chai, Mocha, and Chai HTTP. Even when I return a response of 500, my test case is still passing. Below is my test case: describe('/POST saveBatch', () => { it('it should save ...