Tuesday 11 April 2017

Express.js - Use nested request to get JSON from backup URL

I have two URLs that have a .json.gz file -

var url = "http://post.s3post.cf/s3posts.json.gz";
var backupURL = "https://s3-us-west-2.amazonaws.com/s3post.cf/s3posts.json.gz";

I'm able to successfully use the request module to get json from the file -

app.all('*', function(req, res, next) {
    request({
        method: 'GET',
        uri: url,
        gzip: true
    }, function(error, response, body) {
        res.locals.posts = JSON.parse(body);
        next();
    });
});

What I want to do is, if the request with url fails, I want to use the backupURL to get the json from. So logically, I thought if I received an error, I would use a nested request to do this -

app.all('*', function(req, res, next) {
    request({
        method: 'GET',
        uri: url,
        gzip: true
    }, function(error, response, body) {
        if(error) {
            request({
                method: 'GET',
                uri: backupURL,
                gzip: true
            }, function(error, response, body) {
                res.locals.posts = JSON.parse(body);
                next();
            });
        } else {
            res.locals.posts = JSON.parse(body);
            next();
        }
    });
});

This is not working. Individually, both the URLs work with one request. What can I do to use backupURL when the request with url fails?



via Anish Sana

No comments:

Post a Comment