【问题标题】:How do I receive an http request with a Node.js server and then pass that request along to another server?如何使用 Node.js 服务器接收 http 请求,然后将该请求传递给另一台服务器?
【发布时间】:2025-12-20 20:21:06
【问题描述】:

这里发生了很多事情,所以我将把它简化为一个伪示例。在这里暂时忘掉安全和诸如此类的事情。关键是要了解功能。

假设我正在使用 node.js 运行本地 Web 服务器来开发网站。在网站中,用户应该能够创建一个新帐户。账户信息将通过 ajax 提交到节点服务器。然后,我需要节点服务器接收传入的请求并将其传递给另一台服务器,让我可以访问数据库。例如 CouchDB。

所以这是我希望发生的一个伪示例。

在客户端的浏览器中:

$.ajax({
  url: './database_stuff/whatever', // points to the node web server
  method: 'POST',
  data: {name: 'Billy', age: 24}
});

在 Node Web 服务器中:

var http     = require('http'),
    dbServer = 'http://127.0.0.1:5984/database_url';

http.createServer(function (req, res) {
  /* figure out that we need to access the database then... */

  // magically pass the request on to the db server
  http.magicPassAlongMethod(req, dbServer, function (dbResponse) {

    // pass the db server's response back to the client
    dbResponse.on('data', function (chunk) {
      res.end(chunk);
    });
  })
}).listen(8888);

有意义吗?基本上,将原始请求传递给另一台服务器,然后将响应传回客户端的最佳方式是什么?

【问题讨论】:

    标签: ajax database node.js


    【解决方案1】:

    如果dbServer url 的服务器支持流式传输,您可以执行类似的操作

    var request = require('request');
    req.pipe(request.post(dbServer)).pipe(res)
    

    request 是一个模块,更多信息请看这里https://github.com/mikeal/request

    这是非常可读且易于实现的,如果由于某种原因您无法执行此操作,那么您可以从请求中获取您需要的内容并手动 POST 它,然后将响应和 res.send 它发送给客户端。

    对不起,如果我的代码有错误,我还没有测试过,但我的意思应该很清楚,如果没有,那就问吧。

    【讨论】:

    • 这是一个好方法。对 dbServer 也没有特殊要求。这种方法应该适用于任何 Web 服务器。
    • 这几乎可以满足我的需要。看起来我可以通过管道传输到 dbServer,但我无法通过管道传输回浏览器。
    • 最佳答案是我从几个投票率更高的问题和答案中找到的。谢谢阿尔贝托!