2017-04-11 34 views
0

得到JSON我有有一个.json.gz文件两个网址 -Express.js - 使用嵌套的请求,以便从备用网址

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

我能成功使用请求模块从得到json文件 -

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

我想要做的是,如果与url请求失败,我想用backupURL来从json。所以从逻辑上讲,我想如果我收到一个错误,我会用一个嵌套的请求,要做到这一点 -

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(); 
     } 
    }); 
}); 

这是行不通的。单独地,这两个URL都与一个请求一起工作。当url的请求失败时,如何使用backupURL

编辑1 -

的程序编译,并开始听我的应用程序。这是当我要求它与此错误崩溃页面 -

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) 
+1

“不工作”是没有问题的描述。有后果,详细说明这些。即显示任何错误。您也可以使用一些穷人的调试功能,并添加console.log语句来查看代码需要的路径以及该变量的内容。 – Gimby

+0

@Gimby我编辑了我的问题与错误信息。 –

回答

1

尝试使用response.status 如果是200,然后再移动其他 如果它的400或500,然后使用备用网址

+0

与'200'状态,你也可以得到'HTML',在解析时产生错误 – abdulbarik

+0

@Vipul这工作。我不得不将'if(error)'改成'if(error || response.status!= 200)'。 –

1

它解析错误。

<好像你正在HTML数据,并在第一个位置你得到解析错误

经常检查你的身体前解析

if(typeof body==='string'){ 
    body = JSON.parse(body); 
} 
res.locals.posts = body;