2

I am trying to get an array of image URLs inside Dropbox in JSON format. In order to do that, I have written the following function:

router.get('/thumbnails', function(req, res, next){
var images = [];
var imagesCount = -1;
var isLoggedIn = !!req.user;
var dropboxClient = req.app.get('dropboxClient');
console.log(dropboxClient);
dropboxClient.authenticate({interactive: false}, function(error, client) {
    if (error) {
        console.log(error);
        return 0
    }
    if (dropboxClient.isAuthenticated()) {
        dropboxClient.readdir(dropboxConfig.folder, function(error, entries) {
            if (error) {
                console.log(error);
                return 0
            }
            imagesCount = entries.length;
            entries.forEach(function(entry){
                var path = dropboxConfig.folder + '/' + entry;
                dropboxClient.makeUrl(path, {download: true}, function(err, res){
                    if(err){
                        console.log(err);
                        return 0
                    }
                    //console.log(res.url);
                    images.push({url: res.url});
                    console.log("Processed " + images.length + "/" + imagesCount);
                    if(images.length == imagesCount){
                        console.log(images);
                        res.json(images);
                    }
                });

            });
        });
    }

});

});

Upon observing the console output I believe all URLs are loaded into array, but the data is not available on the address http://.../thumbnails and after a while, if trying to load the data in the browser, it returns ERR_EMPTY_RESPONSE.

Does anyone know why the function doesn't return the data?

Niko Gamulin
  • 66,025
  • 95
  • 221
  • 286
  • It get to `console.log(images)` and don t answer to the request? Or is it failing before? Also, at the time of res.json, you are answering to the dropbox call, not the user's. – DrakaSAN Jul 16 '15 at 10:28

1 Answers1

2
dropboxClient.makeUrl(path, {download: true}, function(err, dbc_res){
    if(err){
        console.log(err);
        return 0
    }

    //console.log(res.url);
    images.push({url: dbc_res.url});
    console.log("Processed " + images.length + "/" + imagesCount);
    if(images.length == imagesCount){
        console.log(images);
        //res come from dropboxClient, not router.get!!!
        res.json(images);
    }
});

The problem is that at res.json, you answer to dropboxClient, not the user, you need to rename res at dropboxClient.makeUrl(path, {download: true}, function(err, res){, so the user get his answer.

DrakaSAN
  • 7,673
  • 7
  • 52
  • 94