如何使用ExpressJS的vhost中间件将子域(business.domain.com)指向已定义的路由(domain.com/business)?
编辑: lukaszfiszer的建议工作并指向正确的路由器,但它不加载任何资产。所以它只是来自玉模板的空白HTML页面。主页面工作正常,只是当你通过vhost访问子域时,资产给出了404.
您可以在此处查看主网站:http://ddbuddyapp.com
您可以在此处查看子域:http://business.ddbuddyapp.com
编辑:以下是修复所有内容且资产正常运行的app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var vhost = require('vhost');
var main = require('./routes/index');
var business = require('./routes/business');
var government = require('./routes/government');
var university = require('./routes/university');
var community = require('./routes/community');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
// Apply Vhost
app.use(vhost('business.localhost', function(req, res, next) {
req.url = "/business" + req.url;
next();
}));
app.use('/', main);
app.use('/business', business);
app.use('/government', government);
app.use('/university', university);
app.use('/community', community);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
// if (app.get('env') === 'development') {
// app.use(function(err, req, res, next) {
// res.status(err.status || 500);
// res.render('error', {
// message: err.message,
// error: err
// });
// });
// }
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
答案 0 :(得分:1)
不是将子应用程序作为第二个参数传递,而是传递一个将转换URL的函数。
var express = require('express');
var vhost = require('vhost');
var app = express();
app.use(vhost('*.domain.com', function(req, res, next) {
req.url = req.url + req.vhost[0];
next();
}));
(...)
app.get('/business', function(req, res) {
res.send('request to business.domain.com received!');
});