app.use not functioning properly within a class in Express

Currently, I am in the process of constructing a WebServer class with the capability to create either an HTTP or HTTPS express webserver. The primary objective of the abstract class is to establish some defaults for the express server. The child class that extends it will subsequently add specific settings based on whether the server is configured for http or https.

However, after implementation, I have observed that when utilizing this.app.use(whateveroption) within the abstract class during server instantiation, the whateveroption assigned to app.use is not being set as intended. In the provided example, the API router cannot be accessed (resulting in timeout errors), and both helmet and morgan functionalities are also not properly configured. Strangely enough, the endpoint at /isalive appears to be functioning correctly. Have I overlooked a key aspect here?

CORRECTED : It seems that my error was due to a typo made in this._app.use(express.json()). The mistake was typing this._app.use(express.json) instead of this._app.use(express.json())

Abstract Class Definition

abstract class WebServer {
  private _app: Express;
  private _routers: IWebServerRoute[] = [];

  constructor() {
    this._applyDefaultToExpressApp();
  }


  private _applyDefaultToExpressApp() {
    this._app = express();
    this._app.get("/isalive", (_, res: Response) => res.status(200).json({ status: "I'm alive" })); // <== endpoint functions correctly
    const apiRouter = Router();
    apiRouter.get("/root", (_, res: Response) => res.status(200).json({ status: "from api root" }));
    this._app.use("/api", apiRouter); // <== encountering timeout issue when accessing localhost:5500/api/root
    this._app.use(express.json);
    this._app.use(
      express.urlencoded({
        extended: true,
      })
    );
    this._app.use(helmet());
    this._app.use(morgan("dev")); // <== no morgan logs appearing in console
  }

  public get app(): Express {
    return this._app;
  }


  abstract createWebServer(serverOptions: http.ServerOptions | https.ServerOptions): http.Server | https.Server;
}

HTTPWebServer Subclass

class HTTPWebServer extends WebServer {
  public server: http.Server;
  constructor(httpOptions?: THTTPWebServerOptions | undefined) {
    super();
  }
  public createWebServer(serverOptions?: http.ServerOptions | undefined): http.Server {
    if (serverOptions) {
      this.server = http.createServer(serverOptions, this.app);
    } else {
      this.server = http.createServer(this.app);
    }
    return this.server;
  }
}

Sample Usage Scenario

 const webServer = new HTTPWebServer();
const server = webServer.createWebServer();
    
      server.listen(port, async () => {
        console.log(`server listen to ${port}`);
      });

Answer №1

Correction: In the code snippet this._app.use(express.json()), I had mistakenly typed this._app.use(express.json) instead of the correct syntax this._app.use(express.json()).

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

Implementing a default parameter in the Express route

It's surprising that I can't seem to locate this information, so it's likely been addressed before (and I may be searching for the wrong thing). Essentially, my question is: Is it possible, and if so, how can I set a default value on a node ...

@ngrx effects ensure switchmap does not stop on error

Throughout the sign up process, I make 3 http calls: signing up with an auth provider, creating an account within the API, and then logging in. If the signup with the auth provider fails (e.g. due to an existing account), the process still tries to create ...

Terminating the program if the initial query yields a result in Node.js Express.js using mongoDB

I have been searching for a solution to this issue for over 2 hours. I am new to working with Express Node MongoDB, and I know the answer is simple but I just can't get it to work. MongoClient.connect(url, function(err, db) { if (err) { r ...

Encountering difficulties retrieving form data in NodeJS Express

I'm currently facing an issue with my form where I am trying to fetch data from the server using ejs templating in my node app. Everything seems fine as there are no errors displayed, but unfortunately, I am unable to retrieve the data in the console. ...

Best practices for working with child components in Vue.js using TypeScript: Steer clear of directly mutating props

I feel like I'm stuck in a loop here. Currently, I have a Vue.js 2 app set up and running with TypeScript. However, I'm encountering an issue when trying to pass data to a child component that originates from the store. <template> < ...

express.js - Issue with session access middleware

I am currently working on a middleware using JavaScript, Express, and Session to restrict access to specific pages based on the existence of a session. Here is my attempt: function checkAdminCredentials(req, res, next) { if (req.session.adminId) { n ...

Having trouble sending props

After successfully writing Jest tests for a React site I created 6 months ago, I decided to work on a new project based off the same codebase. However, when I attempted to write similar tests for basic component rendering, they failed unexpectedly. The er ...

What steps can I take to improve this code and prevent the error "Property 'patient' does not exist on type 'Request<ParamsDictionary>'" from occurring?

I'm having some issues with my code. I am attempting to use passport authenticate in order to save patient information that is specific to the token generated for each individual. router.get("/current", passport.authenticate("jwt", { session: false }) ...

Issue "cannot update headers after they have been sent"

I've been working on a node.js application to retrieve movie listings using the omdb api. However, I'm encountering an error when attempting to access the /result route. The error message is as follows: Error: Can't set headers after they ar ...

Issues with using a personalized font in a Stenciljs project

Looking for guidance on implementing a custom font in my Stenciljs app. I have the otf file, unsure if an npm package is necessary. Here's my code: filestructure: -src --components --assets ---Anurti-Regular.tiff ---Anurti-Regular.ttf friends-l ...

The system couldn't locate the module: Issue: Unable to find module 'fs' within the directory

I am currently working on integrating the ADAL JS sample code from this link into a SharePoint framework client web part. My code is fairly straightforward, as I have already installed packages like adal, fs, and node-fs using NPM. However, when running t ...

The data type 'string' cannot be assigned to the data type 'undefined'

These are the different types available: export type ButtonProperties = { style?: 'normal' | 'flat' | 'primary'; negative?: boolean; size?: 'small' | 'big'; spinner?: boolean; } export type ...

An issue has occurred in my deeply nested reactive form where I am unable to read the properties of null, specifically the 'controls' property

I have encountered an issue with a deeply nested form that communicates with a REST endpoint upon submission. While the first two levels of the form are functioning properly, I am facing numerous challenges when trying to work with the third level. One par ...

tips for effectively mocking useUser, a custom TypeScript hook

Imagine we have a unique custom hook called useUser const useUser = (): IUser => useContext(MiniAppContext).user; This hook is then utilized in another component import { useUser } from '@ABC' const { monitoring } = useUser(); // note that & ...

Unable to include property in Mongoose find query object

After retrieving an object from the MongoDB database, I want to include an additional property before sending it as a response to the frontend using Express. obj = collection.find({}); obj[0].extra_property = "value"; res.send(obj); I am aware t ...

GitHub Alert: Invalid format for environment variable

I am facing an issue with GitHub action. Despite configuring the README.md via a web browser, I encountered an error in GitHub action: Run export BUILD_VERSION=$(grep version package.json | awk -F \" '{print $4}') export BUILD_VERSION ...

How can I send an object to the client using node/express and ejs?

I need to pass a large object to a function in a client script. I attempted using JSON.stringify, but encountered performance issues. Is there an alternative method for achieving this in ejs? app.get('/load', function(req, res) { var data = ...

Encountering some problems while trying to use {return this.getAll.get(this.url)} to consume an API within Angular

I am currently delving into the world of Angular and Typescript to interact with APIs. While I have some experience working with APIs in Javascript, I am relatively new to this setup. The issue I am facing revolves around the code snippet below: To tackle ...

When retrieving all data from a mongoose collection, it sometimes results in receiving a blank list

I recently added a new collection to my project and tried to retrieve all the data from it using the same syntax I used for retrieving users. However, I keep getting an empty array or list. Since I am new to MongoDB, I would appreciate it if someone could ...

Can the return type of a function be determined dynamically at runtime by analyzing a function parameter value?

Let's delve into this concept with an illustrative example! interface Query { foo: any; } interface Mutation { bar: any; } type OperationName = keyof Query | keyof Mutation; const request = async <T>(args, operationName: OperationName): P ...