Node.js上的多个服务器 [英] Multiple servers on Node.js

查看:204
本文介绍了Node.js上的多个服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在同一个nodejs实例上模拟四个服务器(具有不同的主机和端口).

I need to simulate four servers (with different host and port) on the same nodejs instance.

一个例子可能是:

domain1:8000- 域2:8010- 域3:8020- domain4:8030-

domain1:8000 - domain2:8010 - domain3:8020 - domain4:8030 -

有人可以帮助我吗? 谢谢

Can anybody please help me? Thanks

推荐答案

我添加了一个示例,介绍了使用节点的2台服务器的可能解决方案.

I add an example with a possible solution for 2 servers using node.

首先,您需要创建一个项目:

First, you need to create a project:

mkdir simulate4servers
cd simulate4servers
npm init (entry point: index.js)

安装Express:

npm install express --save

将下一个文件放入目录:

Put the next files into the directory:

文件app.js:

'use strict';
const express = require('express');
const app = express();
const routes = require('routes.js');

app.use('/',routes);

module.exports = app;

文件app2.js:

'use strict';

const express = require('express');
const app2 = express();
const routes = require('routes2.js');

app2.use('/',routes);

module.exports = app2;

文件configDomain1.js:

File configDomain1.js:

module.exports = {
    port: 8000
}

文件configDomain2.js:

File configDomain2.js:

module.exports = {
    port: 8010
}

route.js文件:

File routes.js:

'use strict';

const express = require('express');
const api = express.Router();

api.get('/', (req,res)=>{
  res.send({message: 'Hello World!'});
});
module.exports = api;

routes2.js文件:

File routes2.js:

'use strict';

const express = require('express');
const api = express.Router();

api.get('/', (req,res)=>{
  res.send({message: 'Hello World 2!'});
});
module.exports = api;

文件index.js:

File index.js:

'use strict';

const app = require('./app')
const app2 = require('./app2')
const config = require('./configDomain1');
const config2 = require('./configDomain2');

app.listen(config.port, () => {
    console.log(`API REST running in http://localhost:${config.port}`);
});

app2.listen(config2.port, () => {
    console.log(`API REST running in http://localhost:${config2.port}`);
});

最后,运行它:

node index.js

这篇关于Node.js上的多个服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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