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?
EDIT 1 -
The program compiles and starts listening to my app. It is when I request a page that it crashes with this error -
undefined:1
<?xml version="1.0" encoding="UTF-8"?>
^
SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at Request._callback (/Users/Anish/Workspace/NodeJS/unzipper/app.js:65:28)
at Request.self.callback (/Users/Anish/Workspace/NodeJS/unzipper/node_modules/request/request.js:188:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:194:7)
at Request.<anonymous> (/Users/Anish/Workspace/NodeJS/unzipper/node_modules/request/request.js:1171:10)
at emitOne (events.js:96:13)
at Request.emit (events.js:191:7)
at IncomingMessage.<anonymous> (/Users/Anish/Workspace/NodeJS/unzipper/node_modules/request/request.js:1091:12)
at Object.onceWrapper (events.js:293:19)
try to use response.status if its is 200 then move further else if its 400 or 500 then use backup URL