node.js - 创建对象以附加到 Node.js 中的 HTTP 和 HTTPS Express 服务器

标签 node.js express

好的,所以我有一个带有两个快速服务器的 node.js 应用程序。一个在端口 80 (HTTP) 上监听,一个在端口 443 (HTTPS) 上监听。

现在,这些路线并不完全相同。恰恰相反,大多数东西都是通过 HTTPS 提供的,有些是通过 HTTP 提供的。但是,有一些重叠。

所以,我想知道是否有一种方法可以将路由“绑定(bind)”到我所说的 secureApp 和 App,这样我就不必将路由写两次?

例如。现在我有两组相同的路由(一组用于 HTTP,一组用于 HTTPS):

app.get('/tweet-stats.json', function(req, res){
    res.set('Content-Type', 'application/json');
    res.send(publicTweetStatus());
});

secureApp.get('/tweet-stats.json', function(req, res){
    res.set('Content-Type', 'application/json');
    res.send(publicTweetStatus());
});

我想做这样的事情:

model.get('/tweet-stats.json', function(req, res){
    res.set('Content-Type', 'application/json');
    res.send(publicTweetStatus());
});

app.handle.bind(model);
secureApp.handle.bind(model);

这可能吗?我会做更好的编码,我只管理跨所有端口的这个特定路由的一个实例。

最佳答案

你为什么要重复自己?只是阻止不能使用的路由

function secureOnly(req, res, next) {
  if (!req.secure) {
    res.send(426, 'sorry')
  else {
    next()
  }
}

并监听两个端口

http.createServer(app).listen(80)
https.createServer(app).listen(443)

关于node.js - 创建对象以附加到 Node.js 中的 HTTP 和 HTTPS Express 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16474588/

相关文章:

javascript - 如何以类似 JSON 的格式打印循环结构?

linux - Angular/快速托管

express - NestJS - 默认(通配符)路由?

javascript - 为创建 react 应用程序设置代理服务器

javascript - 通过属性获取MongoDB中存储的数组

c++ - NodeJS : node-gyp compile with the equivalent gcc -lm option

node.js - TS2688 : Cannot find type definition file for 'node' with @types/node installed

javascript - 如何在 ubuntu 16,04 上安装 angular-cli?

node.js - Nodejs Express : Routes in separate files

node.js - 在为 Express 应用程序运行 Mocha 测试后关闭 MongoDB 连接