Utilizing Express JS: Invoking a function within my class during routing operations

Currently, I am in the process of developing a MERN Application using Typescript.

I seem to be encountering an issue with this within my class.

When utilizing this code snippet:

router.post("/create", user.createNewUser);

It becomes impossible to call another method from the class user inside the function createNewUser.

However, when using the following snippet instead:

router.post("/create", (req: Request, res: Response, next: NextFunction) => {
    try {
        user.createNewUser(req, res, next);
    } catch (error) {
        res.json(error);
    }
});

It functions correctly.

This is the createNewUser function:

createNewUser(req: Request, res: Response, next: NextFunction) {
    try {
        const { password, username, email, id } = req.body;
        const payload: object = { /* HERE MY JSON */ };
        schema.create(payload, async(err: any, result: any) => {
            const isSended = await this.sendRegistrationEmail(email);
            if (err) throw err;
            if (isSended) {
                res.status(200).json(result);
            } else {
                res.status(500).json('error');
            }
        });

    } catch (error) {
        res.status(500).send(error);
    }
};

The encountered error message is:

TypeError: Cannot read property 'sendRegistrationEmail' of undefined

I am curious as to why the first solution does not work while the second one does.

Answer №1

Understanding the this keyword can be tricky at times. The issue arises when you try to pass a function without its parent object, resulting in the value of this becoming undefined.

An example of this is shown below:
router.post("/create", user.createNewUser);

To solve this problem, you can either use an arrow function like so:

router.post("/create", (...args) => user.createNewUser(...args));

Or you can use the bind method:

router.post("/create", user.createNewUser.bind(user));

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

When integrating Stripe into my Next.js application, I encounter a build error

I encountered an error when building my Next.js app with Stripe integration using "yarn build". However, when running the app locally with "yarn dev", it works perfectly without any errors. I'm struggling to figure out why this discrepancy is happeni ...

How can Angular send datetime data to Nodejs in the most effective manner?

Working with the primeng calendar component within a template-driven form, I encountered an issue. When passing the date 16/05/2018 11:45 from Angular to Node, it gets converted to 2018-05-16T06:15:33.000Z. I discovered that I could convert it back to IST ...

In NextJS, where is the best place to run sensitive code to ensure it is only executed server-side?

I'm currently exploring the world of NextJS and I am in the process of figuring out how to structure my project with a solid architecture that prioritizes security. However, I find myself at a crossroads when it comes to determining the best place to ...

The query pertaining to Facebook redirect functionality

I have a Facebook ad with a URL encoded in it, and I need to extract the final destination URL that it redirects to using JavaScript in my Python program. The standard urllib2/mechanize methods don't work because of the JavaScript involved, and as a P ...

Guide on programmatically redirecting a user to a different route

I am currently working on a VueJS 3 application using Quasar, and I am facing difficulties with programmatically utilizing the Router. The issue can be summarized as follows: 1. The Challenge When attempting to navigate the User to a different route, onl ...

Unexpected behavior: Angular post request does not include the expected request body

Embarking on my initial solo Angular project... I am endeavoring to make a post request to my freshly created web service and have implemented the following code: headers = new HttpHeaders( {'Content-Type':'text/plain'} ); l ...

Guide to utilizing Nginx for serving pages using an express router

Currently, I am in the process of creating a full-stack application with a node.js/mysql backend, react frontend, and utilizing the express router. However, I am encountering difficulties when attempting to set up a local development server. My main requir ...

Generate a new data structure by pairing keys with corresponding values from an existing

Imagine having a type named Foo type Foo = { a: string; b: number; c: boolean; } Now, I am looking to create a type for an object containing a key and a value of a designated type T. The goal is for the value's type to be automatically determin ...

An issue arose during the page prerendering process for "/" on Vercel | Next.js resulting in a deployment error

When attempting to deploy my website using Vercel and generating static pages, I encountered the following error in the logs: info - Generating static pages (0/6) Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/ ...

When a radiobutton is clicked, a jQuery call to a PHP function triggers an AJAX request which results in a JavaScript function becoming unrefer

Currently, I have a situation where two radio buttons are representing different products. When one of them is clicked, the goal is to update the price displayed on the website based on the selected product. Everything seems to be working fine when using t ...

Error encountered while installing npm packages (express, ember)

Recently, I've been attempting to set up ember and express on my Windows 8.1 system for educational purposes. However, I encountered a similar error with both packages while running the command below: npm install -g express-generator To provide bett ...

Using ES6 proxy to intercept ES6 getter functions

I have implemented a proxy to track all property access on instances of a class, demonstrated in the code snippet below: class Person { public ageNow: number; public constructor(ageNow: number) { this.ageNow = ageNow; const proxy = new Proxy( ...

incomplete constructor for a generic class

I have multiple classes that I would like to initialize using the following syntax: class A { b: number = 1 constructor(initializer?: Partial<A>) { Object.assign(this, initializer) } } new A({b: 2}) It seems to me that this ini ...

Using ES6's object destructuring to set default values for nested parameters

Utilizing es6 object destructuring for supplying default parameters to a function. function mapStateToProps({ shops: { cakeShop: {}, pieShop: {} }) { return { CakeShopName: shops.cakeShop.Name, PieShopName: shops.pieShop.Name } } An issue ari ...

Having trouble with executing Mongo import through shell script

I've been attempting to utilize a bash script to import JSON data, but it's not functioning correctly. The error message I'm encountering is: error validating settings: incompatible options: --file and positional argument(s) Here is the co ...

When using the ionic 3 storage.get function, it may return a null value when accessed outside

In regards to storage, the function is returning a null value outside of the function. Below is the code snippet: username:any; this.storage.get('user').then((value) => { this.username = value; }); console.log(this.username); Ou ...

Retrieve information and display it in a text field using ajax

Hi there, I'm having some trouble with my current code and would appreciate any help you can offer. My goal is to filter data in a search box and display the corresponding results in text boxes. I've been searching online for hours trying to find ...

Utilizing Mongodb Aggregation to tally pairs of elements and count individual elements

The data provided includes a series of IDs and corresponding location-service pairs. The goal is to determine the count of unique locations, services, and (location, service) pairs in the dataset. The breakdown of counts for locations: { "_id" : "L3" , "c ...

How can I create a custom checkbox in React Bootstrap without specifying an ID

I'm struggling to understand why this seemingly straightforward Bootstrap custom checkbox isn't functioning as expected. My project involves React, Bootstrap, and React-Bootstrap. import React from "react"; import ReactDOM from "react-dom"; impo ...

utilizing AJAX to send a POST request and display the response in HTML using Django

I am looking to input a number into a text box and retrieve all the even numbers using ajax with Django. Here is my view: load_template @csrf_exempt def load_template(request): if request.method == 'POST': num1 = request.POST[&a ...