ExpressJS - 联系外部API

时间:2012-04-20 03:29:37

标签: node.js express

这是事情: 我有一个客户端将数据发送到服务器。该服务器必须联系外部A.P.I.并将其回复发送回客户端。一旦服务器获得了客户端数据,我就无法弄清楚如何以及在哪里可以联系外部A.P.I。

我像这样路由客户端数据:

app.post('/getAutoComplete', routes.read);

routes.read检索req.body中的数据。使用我的nodejs版本(没有快速框架),然后我以这种方式请求api:

var http = require('http'), options = {
        host : "192.168.1.38",
        port : 8080,
        path : "/myURL",
        method : 'POST'
};

var webservice_data = "";

var webservice_request = http.request(options, function(webservice_response)
{
    webservice_response.on('error', function(e){ console.log(e.message); });
    webservice_response.on('data', function(chunk){ webservice_data += chunk;});
    webservice_response.on('end', function(){res.send(webservice_data);});
});

webservice_request.write(req.body);
webservice_request.end();

问题是我想使用像app.post这样的原生expressJS方法,但我不知道如何因为:

  1. 此处不提供Express(app)对象(在app.js中声明,但在路径文件中未声明)
  2. 我不知道如何使用app.post发送POST数据
  3. 有什么建议吗?

2 个答案:

答案 0 :(得分:2)

app.post('/getAutoComplete', routes.read);
// assuming routes.read lookes something like this
routes.read = function read(req, res) {
  var http = require('http'), options = {
          host : "192.168.1.38",
          port : 8080,
          path : "/myURL",
          method : 'POST'
  };

  var webservice_data = "";

  var webservice_request = http.request(options, function(webservice_response)
  {
      webservice_response.on('error', function(e){ console.log(e.message); });
      webservice_response.on('data', function(chunk){ webservice_data += chunk;});
      webservice_response.on('end', function(){res.send(webservice_data);});
  });

  webservice_request.write(req.body);
  webservice_request.end();
};

同时查看https://github.com/mikeal/request这是在节点中执行Web请求的事实上的模块。

答案 1 :(得分:0)

routes.read是一个功能。您可以使用额外参数调用它,例如

app.post('/getAutoComplete', function(req,res) {
    var q = req.query.q;  // or whatever data you need
    routes.read(q, function(err, response) {
        if (err) throw err;
        return res.json(response);
    });
});

现在让routes.read函数使用第一个参数作为查询,当它从远程API收集响应时,调用第二个参数,任何错误作为第一个参数,响应作为第二个参数。 / p>

更新这个答案已经被选为答案,但如果我展示了routes.read的例子,它会更有帮助:

routes.read = function(q, cb) {
    // pretend we calculate the result
    var result = q * 10;
    if (result > 100) {
        // call the callback with error set
        return cb("q value too high");
    }
    // all is well, use setTimeout to demonstrate
    // an asynchronous return
    setTimeout(function() { cb(null, result) }, 2000);
};
相关问题