Nested routes are not functioning in Express.js with the error message "Cannot GET /apiv1/accounts"

Currently, I am working on developing a backend API using Express with the support of @awaitjs/express.

I'm encountering some challenges when it comes to dealing with 'double nested' endpoints.

For example:

// Within src/routes/routes.ts which serves as an api router file
// apiv1router is exported from this module

app.getAsync('/', (req, res, next) => {
    res.send("I work");
})
-------
// Inside src/server.ts serving as the entry point
app.useAsync('/apiv1', apiv1router);

Accessing /apiv1 functions properly and produces the expected results.

However, when I attempt the following setup:

// src/routes/routes.ts
import { Router } from '@awaitjs/express';
import { router as accountsRouter } from './AccountRoutes/AccountRoutes';

const router = Router();

router.useAsync('/', accountsRouter);

------

// src/routes/AccountRoutes/AccountRoutes.ts
import { Request, Response, NextFunction } from 'express';
import { Router } from '@awaitjs/express';

router.getAsync(
    '/accounts/:accountType',
    async (request: Request, response: Response, next: NextFunction) => {
        try {
            requestValidator(request, next, response);
            const accountsList = await accountModel.find({
                accountType: request.params.accountType,
            });
            response.status(200).json(accountsList);
        } catch (error) {
            return error;
        }
    }
);
export { router as accountsRouter };

And then proceed to visit /apiv1/accounts/foobar, it shows the message

<pre>Cannot GET /apiv1/accounts</pre>
leading to a 404 error
[...] "GET /apiv1/accounts HTTP/1.1" 404 153

Any suggestions or insights on resolving this issue?

In addition to this, above my /apiv1 routing, I have:

import express, { Request, Response, Errback, NextFunction } from 'express';
import { addAsync } from '@awaitjs/express';

import helmet from 'helmet';
import cors from 'cors';
import bodyParser from 'body-parser';
import morgan from 'morgan';
import mongoose from 'mongoose';

const PORT = process.env.PORT;

import { router as apiv1router } from './routes/routes';

const app = addAsync(express());

const mongoURI =
    process.env.MONGOURI;

app.useAsync(express.json());

app.useAsync(helmet());
app.useAsync(cors());


app.useAsync(bodyParser.urlencoded({ extended: true }));

app.useAsync(morgan('common'));

// The error handling middleware for better management
app.useAsync((err: any, req: Request, res: Response, next: NextFunction) => {
    console.error(err.stack);
});

Despite exploring alternate solutions before seeking help, none offered a satisfactory resolution so far.

UPDATE 1 Upon implementing:

router.getAsync(
    '/accounts/:accountType',
    async (request: Request, response: Response, next: NextFunction) => {
      response.json(request.params.accountType)
    }
);

The functionality works flawlessly. Could the culprit be related to mongoose in this context?

Answer №1

Aha! I finally pinpointed the cause of the strange issue.

It appears that stripping away everything related to @awaitjs/express and making the application synchronous resolved all the issues at hand.

Although it may not be the most ideal fix, it effectively addresses the underlying problem of my app being non-functional.

Answer №2

Are you confident in the accuracy of the API URL?

The typical format is /api/v1, not /apiv1

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

Encountering errors pertaining to undefined exports while attempting to package a TypeScript library using webpack

In the process of developing my TypeScript library, I encountered an issue with bundling it using Webpack. Despite trying different configurations and loaders like ts-loader and awesome-ts-loader, I could not get the bundled package to work properly. Every ...

Struggling to concatenate array dynamically in Vue using ajax request

I am working on a Vue instance that fetches objects from a REST endpoint and showcases them on a web page. Most parts of the functionality work smoothly like filtering, however, there is an issue when attempting to add new objects by requesting a new "page ...

Create a search feature using Javascript and React that retrieves and displays results from a

I am currently developing a React application with a search feature that fetches JSON data and displays matching search results on the website import { React, useState } from 'react'; export default function PractitionerSearch() { const [data ...

Transform all the characters within p tags using the JavaScript replace method

Currently, I am dealing with data displayed on my website that comes from an XML feed. However, the issue lies in the fact that the owner of the XML feed has used grave accents (`) instead of apostrophes ('). To address this problem, I have implement ...

Incorporate a different address using $location.path(path); and submit the ng-form

I have a form: <form name="myForm" ng-submit="save(myObject)"> ... <button type="submit" class="btn btn-primary" ng-click="changeLocation('/railway-connection')">Save </button> </form> My goal is to perform two actions w ...

Mapping objects in Typescript to create a union of objects

I have been working on some TypeScript code and I seem to be having trouble getting it to work as expected. It would be greatly appreciated if someone could help me understand what I'm doing wrong or suggest a different approach. Let's assume I ...

Error: Async API Call Triggering Invalid Hook Invocation

When working with my functional component, I encountered an issue while trying to implement a react hook like useMemo or useEffect. It seems that the error may be caused by the asynchronous nature of the API call. In the service file: export const getData ...

Tips for implementing Undefined validations with Lodash

When receiving nested objects in the response, we must traverse to the property and display the values in the user interface. If we have a nested object like this: obj = { parent: { innerchild1: { innerchild2:{ displayText: ...

Preventing Columns in SlickGrid from Being Reordered

Is there a way to prevent specific columns in SlickGrid from being reordered? I have tried looking for a solution but couldn't find one. Unlike the 'resizable' option, there doesn't seem to be an option for each column to allow or disal ...

Is it possible to asynchronously access a JSON object that has been retrieved from a local file on a global scale using the XMLHttpRequest method and

Having some trouble manipulating data from a local JSON file using this technique (no jQuery) as I can't seem to access the object on a global scale: var actual_JSON; function loadJSON(callback) { var xobj = new XMLHttpRequest(); xobj.o ...

Is it possible to retrieve a specific item from an object in a mongo query?

When setting up a compound index like the one below db.data.ensureIndex({ userId: 1, myObject: 1 }) Will the index be used when running the following query? db.data.find({ userId: 1, myObject: { a:'test', b:'test2' } } ...

Access session data without needing the 'req' parameter

Is there a way to check if passportjs is correctly generating the session data without using res.session in a route? For example, can it be accessed like this: router.post("/", function(req,res){ createSessionVariable() console.log(session.newVariable() ...

Sharing tips for sending error objects to a socket.io callback

Utilizing callbacks with socket.io Client side code : socket.emit('someEvent', {data:1}, function(err, result) { console.log(err.message); }); Server side code : socket.on('someEvent', function(data, callback) { callback(ne ...

Applying ngClass to a row in an Angular material table

Is there a way I can utilize the select-option in an Angular select element to alter the css-class of a specific row within an Angular Material table? I have successfully implemented my selection functionality, where I am able to mark a planet as "selecte ...

Tips for utilizing JSON in a TypeScript file within a Node.js environment

I have been working on implementing JSON type in my Node.js application, but I am encountering some data in a scripted format. Here is the response: }, data: '\x1F\b\x00\x00\x00\x00\x00\x00\x00]PMo0\f ...

Transforming a JSON file that has been previously converted to an Observable into a TypeScript map within an Angular application

There is a json data file named dummy, with the following structure: [ {"key":"KEY1", "value":["alpha","beta","gamma"]}, {"key":"KEY2", "value":["A","B","C"]}, {"key":"KEY3", "value":["One","Foo","Bar"]} ] The goal is to convert this json f ...

`How to easily download multiple images with just one click``

I am looking for a way to enable users to download multiple images by simply checking the boxes next to each image and clicking a single button. Currently, I have individual download links below each image. I have added checkboxes next to each image for s ...

Create a document on a different server

I have a file named Sitemap.xml located on Server1, and I am looking to update this file from an alternate server, being Server2. Directory Layout of Server1 Server1: app views public sitemap.xml app.js The Sitemap can be reached via Server1/sitemap s ...

Could my mental model be flawed? When a page is accessed using https, a relative css path will be invoked using the same protocol

When your page is accessed using the https protocol, any relative path to an external CSS file will also be called using the https protocol. Do you really need to encrypt/decrypt CSS content? :D However, if you use an absolute path to reference an external ...

Efficiently serialize data from MongoDB using Express.js without blocking the event loop

My goal is to update this answer without relying on the outdated JSONStream library. The current code snippet looks like this: Comment.find() .cursor() .pipe(JSONStream.stringify()) .pipe(res.type('json')) It utilizes Mongoose's .curs ...