为了避免同域AJAX问题,我希望我的node.js Web服务器将所有请求从URL转发/api/BLABLA到另一个服务器,例如other_domain.com:3000/BLABLA,并且透明地向用户返回该远程服务器返回的相同内容.
所有其他URL(旁边/api/*)将直接提供,不代理.
如何使用node.js + express.js实现此目的?你能给出一个简单的代码示例吗?
(Web服务器和远程3000服务器都在我的控制之下,都运行带有express.js的node.js)
到目前为止,我发现了这个https://github.com/nodejitsu/node-http-proxy/,但阅读那里的文档并没有让我更聪明.我结束了
var proxy = new httpProxy.RoutingProxy();
app.all("/api/*", function(req, res) {
console.log("old request url " + req.url)
req.url = '/' + req.url.split('/').slice(2).join('/'); // remove the '/api' part
console.log("new request url " + req.url)
proxy.proxyRequest(req, res, {
host: "other_domain.com",
port: 3000
});
});
Run Code Online (Sandbox Code Playgroud)
但没有任何东西返回原始的Web服务器(或最终用户),所以没有运气.
在我正在尝试编写的应用程序中,主页面(http:// localhost:8675)具有以下形式:
<form action='/?joinnew' method='post'>
<button>Start</button>
</form>
Run Code Online (Sandbox Code Playgroud)
这是server.js中的代码:
http.createServer(function(request, response) {
var root = url.parse(request.url).pathname.split('/')[1];
if (root == '') {
var query = url.parse(request.url).search:
if (query == '?joinnew') {
var newRoom = getAvaliableRoomId(); // '8dn1u', 'idjh1', '8jm84', etc.
// redirect the user's web browser to a new url
// ??? How to do. Need to redirect to 'http://whateverhostthiswillbe:8675/'+newRoom
...
}}}
Run Code Online (Sandbox Code Playgroud)
如果有办法在我不需要知道主机地址的情况下,我会很高兴,因为这可能会改变.
'http'对象是常规需求('http'),不需要('express').