What is the most effective way to assign req.body values to an attribute of a class?

I am currently working on a class that serves as a controller to execute a method when called from a route. In the list method, I am trying to assign a value to my dataStore attribute without specifying a particular type since I am unsure of what type it should be. The object that is supposed to provide this value is expected to come from req.body.

This implementation is in TypeScript and the requests are being transmitted through Postman.

class RentController{
    private dataStore:any; 

    public search(req:Request, res:Response){
        this.dataStore= req.body; 
        res.send(this.dataStore);
    }
}


Here is the request sent via Postman
Here is the response received via Postman

The error message that I encounter reads:

TypeError: Cannot set property 'dataStore' of undefined

Answer №1

Your code is causing confusion for the compiler because you are using this outside of any defined scope. To resolve this issue, make sure to use

RentController.dataStore = req.body;
instead. This assigns the value of req.body to the dataStore attribute of RentController.

Avoid using this in situations like this as it only adds complexity. Instead, if you need to use the parameter, consider using req.dataStore or res.dataStore, but steer clear of using this.

Answer №2

Your class members are not being initialized with any default value, hence they are currently undefined.

To resolve this issue, try assigning a default value and then check the result to see that value displayed.

class RentController{
    private dataStore:any = {value: 1}; 

    public search(req:Request, res:Response){
        this.dataStore= req.body; 
        res.send(this.dataStore);
    }
}

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

Currently, I am attempting to retrieve text input through the use of AngularJS

Having trouble retrieving text input values using Angular JS? The console keeps showing undefined. <div ng-controller="favouritesController" class="col-xs-12 favList"> <input type="text" ng-model="newFav" ng-keyup= "add($event)" class="col-xs-1 ...

Ways to Retrieve JavaScript Variable inside HTML Tags in a JSP

I am currently facing a requirement where I must assign js variables to html input tag ids. For example: <input type='text' id='(here I need js variable)'/> I am aware that one way to achieve this is by creating the entire elem ...

Reset the form upon submission in AngularJS

Hey, I'm looking to reset the form values after a successful submission. How can I achieve this? <div ng-controller="employeelistController as listControl"> <div class="container form-group" ng-controller="addEmployee as addemp"> ...

Utilizing HTML and JavaScript to dynamically switch stylesheets based on the width of

When it comes to using stylesheets for mobile and non-mobile devices, there is a need for different approaches. The idea of comparing browser height and width in JavaScript seems like a good one, but the implementation may not always work as expected. ...

Using nested asynchronous loops to push items to an asynchronous queue without triggering the main callback

I have an async queue that I am populating with items from nested lists within a data object. Despite the queue processing everything, I am unable to reach my main callback function console.log('All done.'). I've stripped away unnecessary co ...

Traverse through the loop with React Material UI in JavaScript

Hi everyone, I'm having trouble with this code. I want to iterate through an object called paleogenome.data and create a CardHeader for each item: { Object.keys(paleogenome.data).forEach(function (key){ console.log(paleogenome.data[key] ...

Retrieving a database value in Node.js Firestore containing a space

Hello, I'm just getting started with node Js and I anticipate that it will be a smooth ride! Currently working on an application using node JS with Firestore where I need to retrieve data like "display name": James and "Age": 22 Since Age does not h ...

Ensuring that the field is empty is acceptable as long as the validators are configured to enforce

I have successfully created a form using control forms. idAnnuaire: new FormControl('',[Validators.minLength(6),Validators.maxLength(6)]), However, I am facing an issue where when the field is left empty, {{form.controls.idAnnuaire.valid }} is ...

How can I organize the selected options from a select2 form element using a basic sorting method?

I am utilizing select2 by ivaynberg and encountering an issue with the data arrangement upon submission. Is there a method to have the results in the form submit data reflect the order in which they were selected in the select2 element, without relying on ...

Error encountered within the mounted hook in threejs referencing issue

After successfully importing a js file with three.js code into a standard HTML file, I attempted to export/import the code from the external JS file and call it from mounted. However, when doing so, I received an error message stating: "ReferenceError: THR ...

Uninstalling the most recent version of node and going back to an older version is a straightforward

Error: Module 'graphql/validation/rules/KnownArgumentNamesRule' not found. Require stack: - C:\Users\Minseo\AppData\Roaming\npm\node_modules\apollo\node_modules@apo llo\federation\dist\compos ...

The error message "ReferenceError: _ref is not defined"

My journey into React began with just basic knowledge about JavaScript. I am currently working on a server query that handles MySQL, and while the connection is fine, I am encountering an issue with the return. Instead of receiving a JSON response as expec ...

The chaos of Typescript decorators

Are there any strategies for managing extensive decorator usage within classes? Consider this instance of a class property in my NestJS application, featuring an incomplete swagger documentation decorator: @ApiModelProperty({ description: 'des ...

Tips for transforming a JSON Array of Objects into an Observable Array within an Angular framework

I'm working with Angular and calling a REST API that returns data in JSON Array of Objects like the example shown in this image: https://i.stack.imgur.com/Rz19k.png However, I'm having trouble converting it to my model class array. Can you provi ...

One interesting concept: Using Node.js domains for each Express request within another domain

Dealing with Errors in Node - A Frustrating Journey As I work on structuring a simple Node application, the issue of error handling becomes paramount. Cluster -> Worker -> Server Domain -> Express Request Domain The goal is to prevent a serve ...

The specified file path '.../node_modules/@nomicfoundation/hardhat-core/src' could not be located

I have successfully set up a TypeScript hardhat project, but I encountered an issue in /***/node_modules/@nomicfoundation/hardhat-chai-matchers/src/tsconfig.json: { "extends": "../../../config/typescript/tsconfig.json", "compil ...

checkbox with an option tag

I need help with implementing multi-select checkboxes inside an Angular 4 application. The checkboxes are not appearing next to the team names as intended. Can anyone assist me with this issue? Below is a snippet of my HTML code: <select class="form-c ...

Utilize select2 for dynamically loading an external html component

When the page is loaded, it includes another HTML page with a select element that I want to style using select2. The basic page structure looks like this: <select class="selectAddItem" id="selectAddItem" name="selectAddItem" style="width: 150px;" clas ...

When I try to refresh the page, React is unable to show a random selection of listings using the aggregate

I'm currently working on a recipe website where I want to display the recipes in random order every time the page is reloaded. However, I seem to be facing an issue where it only shows "no recipe found" message. I specifically need the recipes to appe ...

Is there a way to update the input box value with a variable using jquery?

I am currently facing an issue with changing the value attribute of an input box in a form using jquery. Although I am able to change the value, it does not reflect in the outer html. Below is my current code snippet: $("a").click(function(event) { va ...