我正在尝试使用 https://github.com/bmullan91/express-subdomain用于 express 中的子域路由。以下是我的 main.js 和 src/routes/site 文件的内容。
const express = require('express');
const bodyParser = require('body-parser');
const subdomain = require('express-subdomain');
const siteRouter = require('./src/routes/site');
const app = express()
app.use(express.json() );
app.use(express.urlencoded());
app.use(express.static('public'));
app.use(subdomain('*.www', siteRouter));
app.get('/', function(req, res) {
res.send('Homepage');
});
const server = app.listen(80,'x3.loc', function () {
var host = server.address().address;
var port = server.address().port;
console.log('X3 listening at http://%s:%s', host, port);
});
const express = require('express');
let router = express.Router();
router.get('/', function(req, res) {
res.send('Welcome to site');
});
module.exports = router;
这种app.use(subdomain('*.www', siteRouter));
的做法已在https://github.com/bmullan91/express-subdomain/issues/33 中提出但不起作用。
我也尝试过仅将 * 作为子域,但这导致没有子域的主页也被视为一个子域。我怎样才能让它工作?
最佳答案
我们知道 /
匹配任何基本路径,而不考虑子域。所以我让你的主页中间件像这样“子域感知”:
app.get('/', function(req, res,next) {
/* If there are any subdomains, skip to next handler, since request is not for the main home page */
if (req.subdomains.length > 0) {
return next();
}
res.send('Homepage');
});
然后我将子域的中间件放在主页中间件下方,如下所示:
app.use(subdomain('*', siteRouter));
这使得主页中间件可以为 x3.loc
和子域中间件服务于任何子域的请求,如 api.x3.loc
或 api。 v1.x3.loc
.
但在我看来,真正的修复应该在模块中完成。我认为应该更改它,以便处理 req.subdomains
为空的情况,或者 *
与实际字符串匹配,而不是跳过迭代。
令我惊讶的是,错误 33 中建议的修复对报告者来说按原样工作。在我的测试中,它以相反的方式工作,即 www.example.com 转到子域中间件,而 stat1.example.com 转到主页中间件。可能是记者看到了,调换了中间件体。
关于javascript - express-subdomain 处理任何子域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47378255/