gpt4 book ai didi

ajax - 如何使用 Node.js 服务器接收 http 请求,然后将该请求传递给另一台服务器?

转载 作者:搜寻专家 更新时间:2023-11-01 00:46:00 24 4
gpt4 key购买 nike

这里有很多事情要做,所以我将把它简化为一个伪示例。在这里暂时忘掉安全性和诸如此类的东西。重点是了解功能。

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

所以这是我希望发生的事情的伪示例。

在客户端的浏览器中:

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

在 Node 网络服务器中:

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);

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

最佳答案

如果 dbServer url 的服务器支持流式传输,你可以做类似的事情

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

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

这是非常可读且易于实现的,如果出于某种原因你不能这样做,那么你可以从请求中获取你需要的内容并手动 POST 它,然后获取响应和 res.send 给客户端。

很抱歉,如果我的代码中有错误,我还没有测试过它,但我的观点应该很清楚,如果没有,请离开。

关于ajax - 如何使用 Node.js 服务器接收 http 请求,然后将该请求传递给另一台服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16680033/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com