2016-04-27 198 views
1

我试图从服务器端(.js文件)一个REST API获取数据,并在我看来,它显示( .jade)REST API的node.js

我能得到的数据,但无法将其发送到视图。 这是我的代码看起来像:

var BugData ='initial data' ; 
var https = require('https'); 

var optionsget = { 
    rejectUnauthorized: false, 
    host : 'My host', // here only the domain name 
    // (no http/https !) 
    port : 443, 
    path : 'Mypath', // the rest of the url with parameters if needed 
    method : 'GET' // do GET 
}; 

console.info('Options prepared:'); 
console.info(optionsget); 
console.info('Do the GET call'); 
// do the GET request 
var reqGet = https.request(optionsget, function(res) { 
    console.log("statusCode: ", res.statusCode); 

     res.on('data', function(d) { 
     console.info('GET result:\n'); 

     BugData =d; 
     console.log('Show Data : ***** \n' +d); 


    }); 

}); 

reqGet.end(); 
reqGet.on('error', function(e) { 
    console.error(e); 
}); 

res.render('index', { ab:BugData}); 

BugData(是以前定义的)是我试图发送到视图中的变量,但由于某种原因,它是空的,不包含变量“d”

有谁知道为什么或者我该如何解决这个问题? 谢谢

+0

你确定它是空的,或者它是一个Buffer对象?如果它是一个缓冲对象,那么你可以用多种方法修复。 (例如'res.setEncoding(“utf8”);') – jmugz3

+0

您的代码从不检查BugData的值,它从不做任何看起来像“发送到视图”的东西 – Quentin

+0

请给出整个代码,您的代码位于何处?路线内? – num8er

回答

1

有没有必要写长码。

是简单的,按照下列步骤:

1)安装请求包:

npm install --save request 

2)路由器的附加的外部:

var request = require('request'); 

process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0; 

3)使用路由器里面的代码:

request.get({url: 'https://my-host/Mypath'}, function(err, response, body) { 
     var data = {}; 

     if (err) { 
      console.error(err); 
      data.err = err; 
     } 

     data.ab = body; 
     console.log('Data: ', data); 

     res.render('index', data); 
}); 
+0

也许他们更喜欢没有使用额外模块的答案? – lauriys

+0

实际要求模块是:a。简单,b。通用的,c。大家广泛使用。作为连接监听器,https模块比请求制造商更好。如果您谈论其他模块:https也是模块。如果您使用https.request()或request.get(),是否有区别?这些都是功能,没有什么特别的,它不会损害性能。 – num8er

+1

非常感谢它现在的作品:) – SIB