The-NodeJS-Master-Class icon indicating copy to clipboard operation
The-NodeJS-Master-Class copied to clipboard

TypeError: Cannot read property in Nodejs

Open dcjayasuriya2020 opened this issue 5 years ago • 8 comments

my code: var firstName = typeof(data.payload.firstName) == 'string' && data.payload.firstName.trim().length >0 ? data.payload.firstName.trim() : false;

but when it runs in git bash, I got the err as : `$ node index.js It's listening on 3200 in staging mode It's listening on 3201 in staging mode file:///E:/Learn/lib/handlers.js:29 var firstName = typeof(data.payload.firstName) == 'string' && data.payload.firstName.trim().length >0 ? data.payload.firstName.trim() : false; ^

TypeError: Cannot read property 'firstName' of undefined at Object.handlers._users.post (file:///E:/Learn/lib/handlers.js:29:41) at handlers.users (file:///E:/Learn/lib/handlers.js:16:37) at IncomingMessage. (file:///E:/Learn/index.js:107:21) at IncomingMessage.emit (events.js:327:22) at endReadableNT (internal/streams/readable.js:1327:12) at processTicksAndRejections (internal/process/task_queues.js:80:21)`

how to resolve this?

dcjayasuriya2020 avatar Jan 14 '21 10:01 dcjayasuriya2020

Hi, @dcjayasuriya2020

i don't see any syntax error with that. I think double check with how you called the function handlers._users.post and also make sure that payload is being supplied in the index.js just as follows: let data = { "trimmedPath": pathTrimmed, "queryStringObject": queryString, "method": method, "headers": headers, "payload": helpers.parseJsonToObject(buffer) };

MakMoinee avatar Jan 17 '21 02:01 MakMoinee

thanx @MakMoinee still confusing Mak, cannot continue to other Methods too.

Here is how Handlers user post function was given:

var handlers = {};

handlers.users=function(data,callback){
    var acceptableMethods = ['post', 'get', 'put', 'delete'];
    if (acceptableMethods.indexOf(data.method)>-1){
        handlers._users[data.method](data,callback);
    }else{callback(405);
    }
};

// Container for the USER Submethods
`handlers._users={};` //{} which is an object .. and on that object we will create the following:

    // Handlers Users Post
    // required data: 1st name, last name, mobile, password, tosAgreemnt(boolean)



'handlers._users.post= function (data,callback){
    //check the all required fields r filled out. check the payload that user give us is in-line with the structure we need, if not let them indicate err, and ask to rectify it
    var firstName = typeof(data.payload.firstName) == 'string' && data.payload.firstName.trim().length >0 ? data.payload.firstName.trim() : false;
//continuing same post function for LastName, Mobile, password, tosAgreement(boolean)`

**Payload in index.js = ** 
`var chosenHandler = typeof(router[trimmedPath]) !== 'undefined' ? router[trimmedPath]: handlers.notfound;

                    //Construct the data object to send to the handler
                    var data ={
                    'trimmedPath' : trimmedPath,
                    'queryStringObject': queryStringObject,
                    'method': method,
                    'headers': headers,
                    'payloads': helpers.parseJsonToObject(buffer)        
                    };`
 

dcjayasuriya2020 avatar Jan 17 '21 04:01 dcjayasuriya2020

Are you having this error during running ? or during triggering it via postman?

MakMoinee avatar Jan 17 '21 07:01 MakMoinee

try replace the handlers._users.post function to this

` handlers._users.post = (data, callback) => { // Check that all required fields are filled out let firstName = typeof (data.payload.firstName) === 'string' && data.payload.firstName.trim().length > 0 ? data.payload.firstName.trim() : false; let lastName = typeof (data.payload.lastName) === 'string' && data.payload.lastName.trim().length > 0 ? data.payload.lastName.trim() : false; let phone = typeof (data.payload.phone) === 'string' && data.payload.phone.trim().length == 11 ? data.payload.phone.trim() : false; let password = typeof (data.payload.password) === 'string' && data.payload.password.trim().length > 0 ? data.payload.password.trim() : false; let tosAgreement = typeof (data.payload.tosAgreement) === 'boolean' && data.payload.tosAgreement === true ? true : false;

if (firstName && lastName && phone && password && tosAgreement) {
    
} else {
    callback(400, { "Error": "Missing required fields" });
}

} `

MakMoinee avatar Jan 17 '21 07:01 MakMoinee

yes exactly, when triggering via POSTMAN, not on running... terminal end/ gitbash, its get the server response but not the postman trigger under the "users" route/ handle

I tried as per ur guide...still the same err:

let firstName = typeof (data.payload.firstName) === 'string' && (data.payload.firstName).trim().length > 0 ? (data.payload.firstName).trim() : false;
                                 ^

TypeError: Cannot read property 'firstName' of undefined
    at Object.handlers._users.post (file:///E:/Learn/lib/handlers.js:30:42)
    at handlers.users (file:///E:/Learn/lib/handlers.js:16:37)
    at IncomingMessage.<anonymous> (file:///E:/Learn/index.js:107:21)

dcjayasuriya2020 avatar Jan 17 '21 11:01 dcjayasuriya2020

Hi @dcjayasuriya2020

I now know why you're getting that error: in your code :

`var chosenHandler = typeof(router[trimmedPath]) !== 'undefined' ? router[trimmedPath]: handlers.notfound;

                //Construct the data object to send to the handler
                var data ={
                'trimmedPath' : trimmedPath,
                'queryStringObject': queryStringObject,
                'method': method,
                'headers': headers,
                'payloads': helpers.parseJsonToObject(buffer)        
                };`
                
                

It seems that you got the wrong spelling the payload. it must be payload not payloads

MakMoinee avatar Jan 18 '21 00:01 MakMoinee

ABSOLUTELY Wow! what a pin sharp... THANK YOU in deed @MakMoinee ... 👍 IT 's working... getting json { "Error": "Missing required fields" } time to get the full body with all data types.... Thank you in deed MakMoinee

But why or what made 'payload' or 'payloads'... what is the science behind it?

dcjayasuriya2020 avatar Jan 18 '21 19:01 dcjayasuriya2020

@dcjayasuriya2020

This is the usual array object. When referencing to a key that its not within the object's key then you will end up having those errors. It means that when you have it as payloads from the object you passed on the handlers then in the handlers you'll probably use data.payloads

MakMoinee avatar Jan 18 '21 21:01 MakMoinee