Search code examples
javascriptnode.jsjsonstringrequest

TypeError: Cannot read property of undefined Node.js


I have a function to get the last backup version of a network node. For this function is given a list of nodes(example value: TEST GROUP WLAN/SW4912), then to get the last backup's version I need to make a request to get a JSON, and the URL has to be like "http://localhost/node/version?node_full=TEST%20GROUP%20WLAN/SW4912&format=json" I'm trying to replace the string and it works but when the script tries to make the request, it is returned for me that cannot read the property 'replace' of undefined.

What is happening?

Stack error:

TEST GROUP WLAN/SW4912
1: TEST GROUP WLAN/SW4912
2: TEST%20GROUP%20WLAN/SW4912
http://localhost/node/version?node_full=TEST%20GROUP%20WLAN/SW4912&format=json
1: undefined
/tmp/relatorio/relatorio.js:28
        string = string.toString().replace(/\s/gi, "%20");
                        ^

TypeError: Cannot read property 'toString' of undefined
    at getLastVersion (/tmp/relatorio/relatorio.js:28:18)
    at Request._callback (/tmp/relatorio/relatorio.js:43:18)
    at Request.self.callback (/tmp/relatorio/node_modules/request/request.js:185:22)
    at Request.emit (events.js:223:5)
    at Request.<anonymous> (/tmp/relatorio/node_modules/request/request.js:1161:10)
    at Request.emit (events.js:223:5)
    at IncomingMessage.<anonymous> (/tmp/relatorio/node_modules/request/request.js:1083:12)
    at Object.onceWrapper (events.js:312:28)
    at IncomingMessage.emit (events.js:228:7)
    at endReadableNT (_stream_readable.js:1185:12)

This is my code (Using nodejs):

const Request = require('request');

const url = 'http://localhost/nodes?format=json';

Request.get({
        url: url,
        json: true,
        headers: {'User-Agent': 'request'}
}, (err, res, data) => {
        if (err) {
                console.log('Error:', err);
        } else if (res.statusCode !== 200) {
                console.log('Status:', res.statusCode);
        } else {
                getLastVersion(data);
        }
});

function getLastVersion(data){
        var string = data[0].full_name;
        
        //string = string.replace(/\s/g, "%20");
        console.log("1: "+string);
        string = string.toString().replace(/\s/gi, "%20");
        console.log("2: "+string);

        var url = `http://localhost/node/version?node_full=${string}&format=json`;
        console.log(url); // until here the function works!
        
        Request.get({
                url: url,
                json: true,
                headers: {'User-Agent': 'request'}
        }, (err, res, data) => {
                if (err) {
                        console.log('Error:', err);
                } else if (res.statusCode !== 200) {
                        console.log('Status:', res.statusCode);
                } else {
                        console.log(data);
                }
        });

}

Thanks for your help!


Solution

  • Your object at the position 0 of your array data might be defined, but it does not seams to have any property full_name. This will cause your string variable to be undefined. You can print it in your console.log ( resulting in the word undefined ) but you can't do any action on it ( like .toString(), which i'm not quite sure is a string function.).

    One way to solve this would be to validate if the object contains a property string before assigning it. There are multiple way to acheive this, here we are using the hasOwnProperty on the object.

    function getLastVersion(data){
            if(data[0].hasOwnProperty('full_name')) {
                // full_name exists
                var string = data[0].full_name;
    
                console.log("1: "+string);
                string = string.toString().replace(/\s/gi, "%20");
                console.log("2: "+string);
                /* ... */
            } else {
               // full_name did not exist.
            }
    }
    

    You could also assign a default value.

    function getLastVersion(data){
                // full_name exists
                var string = data[0].full_name;
    
    
                if(typeof string === 'undefined' || string === null) {
                   string = "some new name";
                }
    
                console.log("1: "+string);
                string = string.toString().replace(/\s/gi, "%20");
                console.log("2: "+string);
                /* ... */
    }