[英]Subdomain (host) based routing in Express
我已经谷歌搜索了一段时间,但找不到任何有用的答案。 我正在尝试在我的网站api.example.com
上获取 api 的子域。 但是,所有答案都说我需要更改我的 DNS 以将api.example.com
重定向到example.com/api
,这是我不想要的。 是否可以只提供api.
而不是重定向到/api
? 我将如何 go 这样做?
const path = require('path'),
http = require('http'),
https = require('https'),
helmet = require('helmet'),
express = require('express'),
app = express();
const mainRouter = require('./routers/mainRouter.js');
// security improvements
app.use(helmet());
// main pages
app.use('/', mainRouter);
// route the public directory
app.use(express.static('public'));
app.use(/* API subdomain router... */)
// 404s
app.use((req, res) => {
res.status(404).sendFile(path.join(__dirname, "views/404.html"));
})
我建议您使用Nginx和单独的api服务。
但是由于某些原因,您无法避免它(或者您不想要它,因为您只想尽快向客户展示原型)。
您可以编写中间件,该中间件将从标头中捕获主机并转发到某些自定义路由器:
1) /middlewares/forwardForSubdomain.js
:
module.exports =
(subdomainHosts, customRouter) => {
return (req, res, next) => {
let host = req.headers.host ? req.headers.host : ''; // requested hostname is provided in headers
host = host.split(':')[0]; // removing port part
// checks if requested host exist in array of custom hostnames
const isSubdomain = (host && subdomainHosts.includes(host));
if (isSubdomain) { // yes, requested host exists in provided host list
// call router and return to avoid calling next below
// yes, router is middleware and can be called
return customRouter(req, res, next);
}
// default behavior
next();
}
};
2)以api路由器为例/routers/apiRouter.js
:
const express = require('express');
const router = express.Router();
router.get('/users', (req, res) => {
// some operations here
});
module.exports = router;
3)在/
处理程序之前附加中间件:
const path = require('path'),
http = require('http'),
https = require('https'),
helmet = require('helmet'),
express = require('express'),
app = express();
const mainRouter = require('./routers/mainRouter');
// security improvements
app.use(helmet());
// ATTACH BEFORE ROUTING
const forwardForSubdomain = require('./middlewares/forwardForSubdomain');
const apiRouter = require('./routers/apiRouter');
app.use(
forwardForSubdomain(
[
'api.example.com',
'api.something.com'
],
apiRouter
)
);
// main pages
app.use('/', mainRouter);
// route the public directory
app.use(express.static('public'));
// 404s
app.use((req, res) => {
res.status(404).sendFile(path.join(__dirname, "views/404.html"));
})
PS它与express-vhost包中的代码相同
Express.js 有一个官方的 vhost 插件: https://github.com/expressjs/vhost
您所描述的由单个服务器托管/处理的多个域/主机名通常称为“vhost”(虚拟主机)。
绝对可以仅将子域(api.example.com)指向您的api服务器。
DNS无法控制子目录,因此example.com/api
的DNS条目无效
如果您有服务器的IP地址,则需要添加一个A记录,其值是: api.example.com
。
如果您拥有服务器的域名,则需要创建一个CNAME记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.