Answer the question
In order to leave comments, you need to log in
Unable to read "length"?
I am getting this error:
Cannot read property 'length' of undefined
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')
}
}
})
> console.log(`body: ${(chunk)}`):
body: {"rowsCount":75,"rows":[..., {"Id":75,"Name":"CEO"}]}
> console.log(typeofchunk):
object
> console.log(typeofchunk.rows):
undefined
chunk.rows
does not have a data type.
Answer the question
In order to leave comments, you need to log in
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?
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 questionAsk a Question
731 491 924 answers to any question