反应路由器路径,SNICallback,POST,GET

时间:2017-10-27 23:07:27

标签: node.js express react-router-v4

我构建了以下快速应用程序,以便从单个服务器使用HTTPS为多个站点提供服务:

// strict
'use strict';

// vars
const tls = require('tls');
var fs = require('fs');
var http = require('http');
var https = require('https');
var express = require('express');
var vhost = require('vhost');
var forceSSL = require('express-force-ssl');
var cors = require('cors');
var app = express();
var server;
var secureServer;

// always force HTTP -> HTTPS redirect
app.use(forceSSL);

// allow cross origin
app.use(cors());

// Express settings (main switch logic - each host, and each static directory)
var siteOne = vhost('siteone.com', express.static('../siteone/dist'));
var wwwSiteOne = vhost('www.siteone.com', express.static('../siteone/dist'));
var siteTwo = vhost('sitetwo.com', express.static('../sitetwo/dist'));
var wwwSiteTwo = vhost('www.sitetwo.com', express.static('../sitetwo/dist'));

app.use(cors()); // allow cross origin
app.use(siteOne); // all hosts defined above
app.use(wwwSiteOne);
app.use(siteTwo);
app.use(wwwSiteTwo);

app.use(function(req, res, next) { // 404 page as last "use" call
  res.status(404).send('404 page :(');
});

// HTTP Server - http.createServer is enough for our HTTP needs
server = http.createServer(app);
server.listen(8080);  // router is set to forward port 80 (http requests) to port 8080

// HTTPS Server - use virtual host to redirect with secureserver
var secureContext = {
    'siteone.com': tls.createSecureContext({
        key: fs.readFileSync('../../sslcert/siteone/privkey.pem', 'utf8'),
        cert: fs.readFileSync('../../sslcert/siteone/fullchain.pem', 'utf8'),
        ca: fs.readFileSync('../../sslcert/siteone/chain.pem', 'utf8'),
    }),
    'www.siteone.com': tls.createSecureContext({
        key: fs.readFileSync('../../sslcert/siteone/privkey.pem', 'utf8'),
        cert: fs.readFileSync('../../sslcert/siteone/fullchain.pem', 'utf8'),
        ca: fs.readFileSync('../../sslcert/siteone/chain.pem', 'utf8'),
    }),
    'sitetwo.com': tls.createSecureContext({
                key: fs.readFileSync('../../sslcert/sitetwo/privkey.pem', 'utf8'),
                cert: fs.readFileSync('../../sslcert/sitetwo/fullchain.pem', 'utf8'),
                ca: fs.readFileSync('../../sslcert/sitetwo/chain.pem', 'utf8'),
    }),
    'www.sitetwo.com': tls.createSecureContext({
                key: fs.readFileSync('../../sslcert/sitetwo/privkey.pem', 'utf8'),
                cert: fs.readFileSync('../../sslcert/sitetwo/fullchain.pem', 'utf8'),
                ca: fs.readFileSync('../../sslcert/sitetwo/chain.pem', 'utf8'),
    }),
}
try {
    var options = {
        SNICallback: function (domain, cb) {
            if (secureContext[domain]) {
                if (cb) {
                    cb(null, secureContext[domain]);
                } else {
                    // compatibility for older versions of node
                    return secureContext[domain];
                }
            } else {
                console.log('Doing nothing. Domain requsted: ' + domain);
            }
        },
       // must list a default key and cert because required by tls.createServer()
        key: fs.readFileSync('../../sslcert/siteone/privkey.pem'),
        cert: fs.readFileSync('../../sslcert/siteone/fullchain.pem'),
    }
    secureServer = https.createServer(options, app);
        secureServer.listen(8043);  // router is set to forward port 443 (https requests) to port 8043
} catch (err){
    console.error(err.message);
    console.error(err.stack);
}

到目前为止,我遇到了POST,GET和react路由器(v4)路径的问题。例如,只要用户从主页启动,但是如果用户直接在网址栏中提供链接(例如siteone.com),则具有react路由器的单个页面站点将工作到每个链接 / somecoolpath)我从网站开关获得404页面。

同样地,我从网站上发布了一条POST,用于将用户的电子邮件添加到url path / add_email上的数据库中......当我发送电子邮件时,我总是收到404 ...

所有这些路径都适用于他们自己的应用程序,但是当我通过这个SNICallback交换机服务时却不行。

我尝试但没有奏效的事情:

vhost中的通配符:

var reactRouterSite = vhost('siteone.com*', express.static('../siteone/dist'));

在SNI回调中重写域:

SNICallback: function (domain, cb) {
    if (domain.includes('siteone')) { // any request from siteone
        domain = 'siteone.com'
    }
    ...

最后一个app.use()语句中的最后一个switch()语句:

app.use(function(req, res, next) { 
    console.log(req);
    switch (req.url) {
      case '/somecoolpath':
        return siteOne;
        break;
      default:
        res.status(404).send('404 page :(');
    }
});

我花了几个小时寻找可能的解决方案,但是甚至没有找到一个带有SNICallback的反应路由器的案例...任何想法我可以尝试?或者有更简单的解决方案吗?

所有站点都托管在其他节点实例中,在端口8081,8082等上表达应用程序。对于所有站点,根页通过此“切换”按预期加载,它只是那些GET / POST URL和复制/粘贴路由器网址不起作用。

2 个答案:

答案 0 :(得分:1)

你可以做的一件事是摆脱vhosts中间件,只需创建一个app.get('*')路由,然后自己检查req.hostname,而不是使用静态目录,渲染模板。我已经使用多个域和多个反应应用来完成此任务。

答案 1 :(得分:1)

从dzm的回复中,我最终确实取出了vhost中间件,而是使用了app.get('*' ...)路由,但我没有渲染模板,而是发现代理最适合我的需求,并使用the http-proxy package。经过一些测试后,反应路由器路径可以直接在浏览器中复制/粘贴并按预期工作,只要存在app.get()app.post()路径,GET / POST方法也可以工作。在网站切换。

替换vhosts / app.use()部分,同时保留代码的其他部分,即SNICallbacksecureContext不变,解决方案如下所示:

// set up proxy server
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({}); // leave options empty --> custom logic below in app.get('*' ...)

// GET paths
app.get('*', function(req, res) {
  // custom logic to handle and proxy the request
  console.log(req.hostname);
  switch (req.hostname) {
    case 'siteone.com':
      proxy.web(req, res, { target: 'http://127.0.0.1:8081' }); // different node server running on local port 8081
      break;
    case 'sitetwo.com':
      proxy.web(req, res, { target: 'http://127.0.0.1:8082' }); // different node server running on local port 8082
      break;
    default:
      res.status(404).send('404 page :(');
      break;
  }
});

// POST paths (for siteone)
app.post('/new_email', function(req, res) {
  proxy.web(req, res, { target: 'http://127.0.0.1:8081' }); // this post path must also be written on the index.js of siteone.com
});