首页 > 解决方案 > TypeError:无法读取未定义 Node.js 的属性

问题描述

我有一个功能来获取网络节点的最后一个备份版本。对于此函数,给定一个节点列表(示例值:TEST GROUP WLAN/SW4912),然后要获取最后一个备份的版本,需要请求获取 json,并且 url 必须类似于“ http://localhost /node/version?node_full=TEST%20GROUP%20WLAN/SW4912&format=json " 我正在尝试替换字符串并且它可以工作,但是当脚本尝试发出请求时,我无法读取未定义的属性 'replace' .

怎么了?

堆栈错误:

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)

这是我的代码(使用 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);
                        getLastVersion(data)
                }
        });

}

感谢帮助!

标签: javascriptnode.jsjsonstringrequest

解决方案


0您的数组位置的对象data可能已定义,但它没有任何属性的接缝full_name。这将导致您的string变量未定义。您可以在您的console.log(产生单词undefined)中打印它,但您不能对其执行任何操作(例如.toString(),我不太确定它是一个字符串函数。)。

解决此问题的一种方法是string在分配对象之前验证对象是否包含属性。有多种方法可以实现这一点,这里我们使用hasOwnProperty对象上的。

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.
        }
}

您也可以指定一个默认值。

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);
            /* ... */
}

推荐阅读