NodeJS将结果从HTTPS请求传递到视图

时间:2016-07-17 16:19:19

标签: node.js view https routes

我正在向API(wrike.com)发出HTTPS请求,除了我努力将结果传递给我的视图以便在前端显示之外,所有工作都在工作。

这是功能代码:

module.exports.getWrikeFolder = function(user, callback) {
User.findOne({email: user}, function(err, doc){
if(err) throw err;
var accessToken = doc.wrikeaccess;
console.log(accessToken);

var data = querystring.stringify({
  "descendants": true,
  "project": false
});

var options = {
  host: 'www.wrike.com',
  method: 'GET',
  path: '/api/v3/folders/',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': 'bearer ' + accessToken
  }
}

var folders = [];

var request = https.request(options, function(res) {
  res.on('data', function (chunk) {
    folders.push(chunk);
  }).on('end', function() {
    folders = Buffer.concat(folders).toString();
    console.log(folders);
  });

});

request.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

request.write(data);
request.end(err, folders);
});
}

这是路线的代码:

router.get('/dmd', ensureAuthenticated, function(req, res, next) {
wrike.getWrikeFolder(user, function(err, folders) {
    //if(err) throw err;
    res.render('dmd-codes', {
        title: 'DMD Codes',
        nav: 'Admin',
        folders: folders
    });
  });
});

我知道该函数有效,因为console.log(folders);行显示了控制台中的预期结果。为了让结果进入路线,我错过了什么。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您似乎永远不会在向API发出http请求的模块中执行callback,这意味着res.render()无法执行。尝试在callback内添加getWrikeFolder()的执行:

module.exports.getWrikeFolder = function(user, callback) {
  User.findOne({email: user}, function(err, doc){
    // if(err) throw err; // NOOOO! Use callbacks ;)
    if (err) return callback(err);

    // ... (your code)

    var request = https.request(options, function(res) {
      res.on('data', function (chunk) {
        folders.push(chunk);
      }).on('end', function() {
        folders = Buffer.concat(folders).toString();
        console.log(folders);

        // make sure to execute callback!
        callback(null, folders);

      });

    });

    request.on('error', function(e) {
      console.log('problem with request: ' + e.message);
      // don't forget to use the callback!!
      return callback( new Error('problem with request: ' + e.message) );
    });

    request.write(data);
    request.end(err, folders);
  });
}