julekgwa julekgwa - 18 days ago 7
Javascript Question

request with JSON returns empty body Nodejs

I'm using

request
to get a list of movies from yts.ag/api, and display them in grid of thumbnails, when I click on each of the thumbnail I'm taken to another page which display more details of the movie, when I click the thumbnail first time the data is retrieved, the next time when I click the same movie or other movies the
body
is empty, I'll have to restart the server for it work and it only works with one request after the
request
returns an empty
body
. What seems to be the problem or am I implementing
request
wrong?

var express = require('express');
var router = express.Router();
var request = require('request');
var url = 'https://yts.ag/api/v2/movie_details.json';

router.get('/:id', function (req, res, next) {
url += '?movie_id=' + req.params.id;
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
if (body) {
var importJSON = JSON.parse(body);
res.render('movie', {title: 'Hypertube - Torrent streaming', moviedetails: importJSON.data.movie});
}else {
res.render('movie', {title: 'Hypertube - Torrent streaming', moviedetails: false});
}
}
});
});

module.exports = router;

str str
Answer

You are adding the query string containing movie_id to the request URL over and over again. So only the first request will work while all subsequent requests have an invalid request URL. Instead create a new request URL in your request callback. In addition, you just ignore any errors that you might get.