Express.js Router does not recognize the term 'this'

Greetings and thank you for taking the time to peruse through this. I am venturing into the realm of express.js and typescript and have stumbled upon an intriguing issue. I am currently trying to unravel the mystery behind why 'this' is undefined in the functions of CompanyRouter.

The initialization of the router appears as follows:

this.express.use('/api/v1/company', new CompanyRouter(new CompanyService()).router);

Could it be a matter of context, or does express.js view router functions as static functions?

import {Router, Request, Response, NextFunction} from 'express';
import {Company} from '../models/Company';
import {ICompanyService} from '../interfaces/ICompanyService';

export class CompanyRouter {
    router: Router
    service: ICompanyService

    constructor(service : ICompanyService) {
        this.router = Router();
        this.service = service;
        this.init();
    }

    init() {
        this.router.get('/', this.getAllCompanies);
        this.router.post('/', this.postCompany);
    }

    public async getAllCompanies(req: Request, res: Response, next: NextFunction) {
        const companies = this.service.findAll()
        res.send(companies);
    }

    public async postCompany(req: Request, res: Response, next: NextFunction) {
        const company = this.service.add(req.body);
        res.send(company);
    }
}

Answer №1

It seems like the issue lies in how your methods are being called within the init() function. By passing the reference of the function instead of calling it directly, you might be causing this to become undefined as it loses its reference.

To resolve this, consider using the following code:

import {Router, Request, Response, NextFunction} from 'express';
import {Company} from '../models/Company';
import {ICompanyService} from '../interfaces/ICompanyService';

export class CompanyRouter {
    router: Router
    service: ICompanyService

    constructor(service : ICompanyService) {
        this.router = Router();
        this.service = service;
        this.init();
    }

    init() {
        this.router.get('/', (req, res, next) => this.getAllCompanies(req, res, next));
        this.router.post('/', (req, res, next) => this.postCompany(req, res, next));
    }

    public async getAllCompanies(req: Request, res: Response, next: NextFunction) {
        const companies = this.service.findAll()
        res.send(companies);
    }

    public async postCompany(req: Request, res: Response, next: NextFunction) {
        const company = this.service.add(req.body);
        res.send(company);
    }
 }

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

NextJS: Error - Unable to locate module 'fs'

Attempting to load Markdown files stored in the /legal directory, I am utilizing this code. Since loading these files requires server-side processing, I have implemented getStaticProps. Based on my research, this is where I should be able to utilize fs. Ho ...

Structured similar to a map with typed elements

As a beginner in Typescript, I am delving into creating a typed map structure where the values are associated with specific keys. This can be demonstrated through pseudo JS code without types: const propertyA = "PropertyA"; const propertyB = "PropertyB"; ...

Transform Client - Server command-line interface Node.js application into a Docker container

My Node.js application consists of two separate components: an Express.js server and a CLI built with vanilla JavaScript and inquirer.js. These components communicate with each other through a REST API. The main reason for this setup is to adhere to the SO ...

Angular - Highlight a section of a string variable

Is there a way to apply bold formatting to part of a string assigned to a variable? I attempted the following: boldTxt = 'bold' message = 'this text should be ' + this.boldTxt.toUpperCase().bold() ; However, the HTML output is: thi ...

Get the data from the files in the request using request.files in Node.js

Is there a way to read the content of a file (either a txt or CSV file) that a user uploads without saving it to local storage? I know I can save the file in an upload directory and then read it from storage. However, I'm wondering if there is a way ...

Sharing data across multiple paths

route.post('/register',function(req,res){ //completed registration process // token value assigned as 'abc' }) route.post('/verify',function(req,res){ // How can I retrieve the token ('abc') here? }) I' ...

What exactly are the implications of having dual type declarations in TypeScript?

I recently came across the Angular tutorial here In the code snippet below, there are double type declarations that I am having trouble understanding. handleError<T>(operation = 'operation', result?: T) { return (error: any): Observabl ...

How can I utilize Angular services to transfer a count value to the Component?

I've been working on creating a coin counter for my application by developing a service specifically for counting coins. However, when I tried to use this service in one of my components where the count function is triggered, I encountered some diffic ...

In TypeScript, it can be challenging to determine the equality between a value and an enum

I am encountering an issue with my simple code: enum Color { BLUE, RED } class Brush { color: Color constructor(values) { this.color = values.color } } let JSON_RESPONSE = `{"color": "BLUE"}` let brush = new Brush(JSON.parse(JSON ...

In ExpressJS, it is imperative to consistently utilize middleware for smooth and

Is it possible to ensure that an expressjs middleware is always executed, even if there is an error in the next() or not? For example: app.get('/',[middle1,middle2],doIt) In this scenario, middle2 should always execute last, regardless of any ...

Is there a way to automatically determine the parameters of a constructor to match the default class type in TypeScript

I need a function in a class that can utilize a type from constructor arguments, but I am unsure how to achieve this. class CustomClass<Type1, Type2=any>{ a: string = 'a' constructor(private readonly parameters: { attributes: Type ...

Is there a way for me to receive the status code response from my backend server?

My component makes a call to a servlet, which then sends a POST HTTP request to the backend (using Spring Boot). I want the backend to return the status of the POST request that was sent earlier. This is my code: res= this.CS.postcompetenze(this.comp) Th ...

Express server utilizing Node.js for file streaming

As I embark on creating a file streaming server using Node.js, I've noticed that many resources online recommend using express.js. I'm wondering if this is truly the best approach for developing a file server. However, when attempting to install ...

Querying Mongoose to search for a particular value within an array of elements

My schema looks like this: var EntitySchema = new Schema({ name : {type: String, default: null}, organizations : [{ id: { type: mongoose.Schema.Types.ObjectId, ref: 'Organization' }}] }); I have the id of an organization ...

Next.js API is throwing a TypeError because req.formData is not a recognized function

Below is the code snippet for the Next.js route I am working on: import { NextRequest, NextResponse } from 'next/server'; export const config = { runtime: 'edge', }; export default async function POST(req: NextRequest): Promise< ...

Angular version 6 and its routing functionality

Hey there, I need some help with setting up routers in my Angular app. Here is the code from my files: import {NgModule} from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; const APP_ROUTES: Routes = [ {pa ...

typescript makeStyles() functions from material-ui library

I've been struggling to find the correct type without relying on any. I have a working code that styles the component as expected: import { makeStyles } from '@material-ui/core/styles' const useStyles = makeStyles((theme) => ({ mainC ...

Is there a way to modify the style when a different rarity is selected in Next.JS?

Is there a way to change the style depending on the rarity selected? I am currently developing a game that assigns a random rarity upon website loading, and I am looking to customize the color of each rarity. Here is how it appears at the moment: https:/ ...

After successfully logging in, the deployed server encounters an Error 503 and shuts down. However, on the development environment, everything runs smoothly as

I am currently in the process of developing an application using NET 6 LTS and Angular 14. Everything runs smoothly on my development environment with IIS express. However, once I deploy the application (release version) on Windows 2019 with IIS 10, I enco ...

When compiling my TypeScript file, I encountered an error stating that a block-scoped variable cannot be redeclared

In my Visual Studio Code, I have written just one line of code in my ex1.ts file: let n: number = 10; Upon compiling using the command tsc ex1.ts, the compiler successfully generates the ex1.js file. However, VSC promptly displays an error in the .ts file ...