NodeJS Express - 两个端口上的单独路由

时间:2015-02-27 00:12:00

标签: node.js express routes ports

我有一个快速服务器,在构建它时在自己的路由上创建了几个“帮助”功能。我希望在不同的端口上访问这些路由。反正有没有在快递中做到这一点?

在下面的代码中,“/ factory”路由(和其他功能)将位于一个端口上,“/ killallthings”,“/ listallthings”和“/ killserver”的帮助路由将在一个单独的端口上港口。

以下是代码的简化版本:

var express = require('express');
var things = [];
var app = express();
var port = 8080; 

app.post('/factory/', function(req, res) {
  //Create a thing and add it to the thing array
});

//Assume more functions to do to things here....

app.post('/killallthings/', function(req, res) {
  //Destroy all the things in the array
});

app.post('/listallthings/', function(req, res) {
  // Return a list of all the things
});

app.post('/killserver/', function(req,res){
  //Kills the server after killing the things and doing clean up
});

//Assume https options properly setup.

var server = require('https').createServer(options, app);

server.listen(port, function() {
    logger.writeLog('Listening on port ' + port);
});

这可以用快递吗?

2 个答案:

答案 0 :(得分:31)

根据上面的Explosion Pills建议,我大致以这种方式修改了代码:

var express = require('express');
var things = [];
var app = express();
var admin_app = express();
var port = 8080; 
var admin_port = 8081;

app.post('/factory/', function(req, res) {
  //Create a thing and add it to the thing array
});

//Assume more functions to do to things here....

admin_app.post('/killallthings/', function(req, res) {
  //Destroy all the things in the array
});

admin_app.post('/listallthings/', function(req, res) {
  // Return a list of all the things
});

admin_app.post('/killserver/', function(req,res){
  //Kills the server after killing the things and doing clean up
});

//Assume https options properly setup.

var server = require('https').createServer(options, app);

server.listen(port, function() {
    logger.writeLog('Listening on port ' + port);
});

var admin_server = require('https').createServer(options, admin_app);

admin_server.listen(admin_port, function() {
    logger.writeLog('Listening on admin port ' + admin_port);
});

我希望我知道如何将爆炸药作为答案的功劳! :)

答案 1 :(得分:0)

如果您正在尝试创建多个服务器,那么为什么不创建具有不同端口和配置的多个bin / www文件。另一种方法是直接从命令行传递端口号。