gpt4 book ai didi

javascript - Express 中基于子域(主机)的路由

转载 作者:太空宇宙 更新时间:2023-11-04 00:00:47 25 4
gpt4 key购买 nike

我已经用谷歌搜索了一段时间,但找不到任何有用的答案。我正在尝试在我的网站 api.example.com 上获取 api 的子域。但是,所有答案都表明我需要更改 DNS 以将 api.example.com 重定向到 example.com/api,但我不希望这样做。是否可以只提供 api. 而不是重定向到 /api?我该如何去做呢?

  1. 我正在使用 express 。
  2. 我不想使用任何其他非内置软件包。
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 服务。

但是由于某些原因你无法避免它(或者你不想要它,因为你只想尽快向客户展示原型(prototype))。

您可以编写中间件来捕获 header 中的主机并将其转发到某个自定义路由器:

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"));
})

附注它的作用与express-vhost中的相同。包,look at the code

关于javascript - Express 中基于子域(主机)的路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54791634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com