lie*_*erg 3 javascript subdomain routes node.js express
我已经用谷歌搜索了一段时间,但找不到任何有用的答案。我正在尝试为我的网站上的 api 获取子域api.example.com。然而,所有答案都说我需要将 DNS 更改为重定向api.example.com到example.com/api,但我不希望这样做。是否可以只提供服务api.而不是重定向到/api?我该怎么做呢?
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"));
})
Run Code Online (Sandbox Code Playgroud)
我建议您使用 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();
}
};
Run Code Online (Sandbox Code Playgroud)
2)以api路由器为例/routers/apiRouter.js:
const express = require('express');
const router = express.Router();
router.get('/users', (req, res) => {
// some operations here
});
module.exports = router;
Run Code Online (Sandbox Code Playgroud)
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"));
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3490 次 |
| 最近记录: |