R
R
rausuj2019-03-06 13:51:08
Node.js
rausuj, 2019-03-06 13:51:08

Unable to read "length"?

I am getting this error:

Cannot read property 'length' of undefined

There is an error on this line: request:
for (var i = 0; i < chunk.rows.length; i++ ) {
request(
    {
        url: 'http://localhost:5000/positions/get',
        method: 'POST',
        headers: headers
    }, 
    function (error, response, body) {
        console.log('status: ' + response.statusCode)
    }
)
.on('data', function (chunk) {
    console.log(`body: ${(chunk)}`)
    console.log(typeof chunk)
    console.log(typeof chunk.rows)
    var formData = {Id: 75, Name: 'CEO'}
    for (var i = 0; i < chunk.rows.length; i++ ) {
        if (chunk.rows[i].Name === formData) {
            console.log('OK')
        } else {
            console.log('NO')
        }
    }
})

The answers I get
> console.log(`body: ${(chunk)}`):

body: {"rowsCount":75,"rows":[..., {"Id":75,"Name":"CEO"}]}

> console.log(typeofchunk):

object
> console.log(typeofchunk.rows):

undefined
How to fix something that chunk.rowsdoes not have a data type.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Bogdanov, 2019-03-06
@rausuj

Chunk looks like a JSON string or some similar data structure. Perhaps, before accessing the properties, it should be parsed into a "correct" JS object?

S
SagePtr, 2019-03-06
@SagePtr

I can assume that chunk is a string and before taking the rows field from there, you need to do JSON.parse with it. But it's better to do this when the entire line is loaded (that is, not process it in the 'data' event handler, which is called many times with each small portion of new data loaded, but in the callback function passed to the request function as the last parameter) . Otherwise, your code will only work with small responses that fit into one package.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question