简体   繁体   English

REST API node.js

[英]REST API node.js

I am trying to retrieve data from a REST API in the server side ( .js) and display it in my view ( .jade)我正在尝试从服务器端 ( .js)的 REST API 检索数据并将其显示在我的视图中 ( .jade)

I was able to get the data but was not able to send it to the view .我能够获取数据,但无法将其发送到视图。 This is how my code looks like :这是我的代码的样子:

 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 (was defined before )is the variable i am trying to send to the view but for some reasons it is empty and does not contain the variable 'd' BugData(之前定义)是我试图发送到视图的变量,但由于某些原因它是空的并且不包含变量“d”

Does anyone know why or how can i solve this ?有谁知道为什么或我该如何解决这个问题? Thanks谢谢

There is no need to write that long code.没有必要写那么长的代码。

Be simple, follow these steps:很简单,请按照以下步骤操作:

1) install request package: 1)安装请求包:

npm install --save request

2) outside of router add: 2)路由器外添加:

var request = require('request');

process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;

3) use this code inside router: 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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM