node.js:将请求路由到同一主机上的其他端口 [英] node.js: route request to different port on same host

查看:114
本文介绍了node.js:将请求路由到同一主机上的其他端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一台主机,可以提供许多Web应用程序(不是基于node.js的).它使用不同的端口执行此操作.这意味着例如以下应用程序处于活动状态:

I have a host computer which serves a number of webapplications (not node.js based). It does this using different ports. This means that for example the following applications are live:

  • app1:http://主机名:3000
  • app2:http://主机名:3001
  • app3:http://主机名:3003
  • app1: http://hostname:3000
  • app2: http://hostname:3001
  • app3: http://hostname:3003

接下来,我有一个基于node.js的webapp(在端口80上运行),我想将其用作路由器.当有人导航到 http://localhost/app/app1 时.我希望它导航到 http://hostname:3000 .使用简单的重定向,这相对简单.但是,我想保留URL http://localhost/app/app1 .有人可以指出我使用node.js/express进行这项工作的方法吗?

Next to that I have a node.js based webapp (running on port 80) which I want to use as a sort of router. When someone navigates to http://localhost/app/app1. I want it to navigate to http://hostname:3000. This is relatively straightforward using a simple redirect. However, I would want to preserve the url http://localhost/app/app1. Can someone point me to a way to make this work using node.js/express?

我的路由逻辑看起来有点像这样(伪代码).

My routing logic looks somewhat like this (pseudo-code).

app.route('/app/:appName')
   .get(appEngine.gotoApp);

appEngine.gotoApp = function(req, res) {
    redirectToApp logic 
    }

推荐答案

如果使用express,则可以尝试使用cli express应用程序生成器来创建应用程序.

If you use express, you can try to create the app with the cli express application generator.

它将创建一个快速应用程序,并将其与模块导出一起返回.

It creates an express app and returns it with module exports.

在server.js文件中,它传递了快递应用对象的服务器实例的侦听功能.

In the server.js file it pass to listen function of the server instance the express app object.

您可以创建更多服务器对象,并使用不同的端口监听不同的应用程序.

You can create more server object and listen different app with different port.

var server = http.createServer(app);
server.listen(port);
var server2 = http.createServer(app2);
server2.listen(port2);

如果您要基于url指向其他应用,则可以实例化快速路由器而不是快速对象.

If you want to point different app based on the url, you can instance an express router instead of express object.

var app1 = express.Router();

然后,您可以使用经典的get或post或其他方法将所有路线设置到该对象中.

Then you can set all your routes into this object with classic get or post or other methods.

现在,您可以将路由器作为主要Express应用程序的中间件来传递.

Now you are able to pass the router as a middleware of your main express app.

app.use( "app1/", app1 );

您还可以将快速应用程序传递给中间件,而不是路由器对象,以通过不同的URL和端口服务器侦听来执行该应用程序.

You can also pass an express app to middleware, instead of router object, in order to gain the possibility of exec the app with a different url and port server listening.

这篇关于node.js:将请求路由到同一主机上的其他端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆