简体   繁体   English

类型错误:无法读取未定义的 Node.js 的属性

[英]TypeError: Cannot read property of undefined Node.js

I have a function to get the last backup's 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 a 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 try to make the request is returned for me that cannot read property 'replace' of undefined.对于此函数,给出一个节点列表(示例值:TEST GROUP WLAN/SW4912),然后要获取上次备份的版本,需要发出请求以获取 json 并且 url 必须类似于“ http://localhost” /node/version?node_full=TEST%20GROUP%20WLAN/SW4912&format=json “我正在尝试替换字符串并且它可以工作,但是当脚本尝试向我发出请求时,我无法读取未定义的属性“替换” .

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

}

Thanks to help!感谢帮助!

Your object at the position 0 of your array data might be defined, but it does not seams to have any property full_name .您的数组data位置0处的对象可能已定义,但它不具有任何属性full_name This will cause your string variable to be undefined.这将导致您的string变量未定义。 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.).您可以在console.log打印它(导致单词undefined ),但您不能对其进行任何操作(例如.toString() ,我不太确定它是一个字符串函数。)。

One way to solve this would be to validate if the object contains a property string before assigning it.解决此问题的一种方法是在分配之前验证对象是否包含属性string There are multiple way to acheive this, here we are using the hasOwnProperty on the object.有多种方法可以实现这一点,这里我们在对象上使用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.
        }
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Node.js和jdbc:TypeError:无法读取undefined的属性&#39;url&#39; - Node.js and jdbc : TypeError: Cannot read property 'url' of undefined 类型错误:无法读取 Node.js 和 puppeteer 中未定义的属性“匹配” - TypeError: Cannot read property 'match' of undefined in Node.js and puppeteer Node.js和mongodb:TypeError:无法读取未定义的属性&#39;findAll&#39; - Node.js and mongodb: TypeError: Cannot read property 'findAll' of undefined “类型错误:无法读取未定义的属性‘状态’”node.js - "TypeError: Cannot read property 'status' of undefined" node.js TypeError:无法读取未定义的属性“getProperty”? Node.js,傀儡师 - TypeError: Cannot read property 'getProperty' of undefined? Node.js, Puppeteer Node.js TypeError:无法读取未定义的属性“作者” - Node.js TypeError: Cannot read property 'author' of undefined 类型错误:无法读取未定义的属性“findAll” - Node.js + Postgresql - TypeError: Cannot read property 'findAll' of undefined - Node.js + Postgresql Node.js TypeError:无法读取未定义的属性“主机” - Node.js TypeError: Cannot read property 'host' of undefined Node.js-TypeError:无法读取未定义的属性“ document” - Node.js - TypeError: Cannot read property 'document' of undefined Node.js中的TypeError:无法读取未定义的属性“ 0” - TypeError in node.js: cannot read property '0' of undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM