Jason Jason - 2 months ago 14
Javascript Question

Unable to send numbers using res.send() using express with node

I am trying to get the "imdb rating" using express in node and I am struggling.

movies.json

[{
"id": "3962210",
"order": [4.361276149749756, 1988],
"fields": {
"year": 2015,
"title": "David and Goliath",
"director": "Timothy A. Chey"
},
"doc": {
"_id": "3962210",
"_rev": "1-ac648e016b0def40382d5d1b9ec33661",
"title": "David and Goliath",
"year": 2015,
"rating": "PG",
"runtime": "92 min",
"genre": ["Drama"],
"director": "Timothy A. Chey",
"writer": ["Timothy A. Chey"],
"cast": ["Miles Sloman", "Jerry Sokolosky", "Makenna Guyler", "Paul Hughes"],
"poster": "http://ia.media-imdb.com/images/M/MV5BMjA3OTQ4NDc4MV5BMl5BanBnXkFtZTgwNDYwMzA1MjE@._V1_SX300.jpg",
"imdb": {
"rating": 8.4,
"votes": 138,
"id": "tt3962210"
}
}
}, {
"id": "251656",
"order": [3.489020824432373, 686],
"fields": {
"year": 1999,
"title": "David Cross: The Pride Is Back",
"director": "Troy Miller"
},
"doc": {
"_id": "251656",
"_rev": "1-2d0762776874f94af8f2d76e5991b529",
"title": "David Cross: The Pride Is Back",
"year": 1999,
"rating": null,
"runtime": "55 min",
"genre": ["Comedy"],
"director": "Troy Miller",
"writer": ["David Cross"],
"cast": ["David Cross", "Molly Brenner", "Amiira Ruotola"],
"poster": "http://ia.media-imdb.com/images/M/MV5BODcwMjMxOTU4OF5BMl5BanBnXkFtZTgwODE0MTc4MTE@._V1_SX300.jpg",
"imdb": {
"rating": 7.9,
"votes": 380,
"id": "tt0251656"
}
}
}]


results

res.send(result.rows[0].doc.imdb);
returns
{"rating":8.4,"votes":138,"id":"tt3962210"}


but

res.send(result.rows[0].doc.imdb.rating);
// does not return 8.4, just crash's node

and

res.send(result.rows[0].doc.title);
// returns David and Goliath

res.send(result.rows[0].doc.cast[0]);
// returns Miles Sloman

Where am I going wrong?

Answer

According to Express res.send([body]) docs:

The body parameter can be a Buffer object, a String, an object, or an Array

You can't send a number by itself.

Try either converting the number to a string

res.send(''+result.rows[0].doc.imdb.rating);

or send it as an object value

res.send({ result: result.rows[0].doc.imdb.rating});