Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 使用带有子域的ExpressJS路由器_Node.js_Express - Fatal编程技术网

Node.js 使用带有子域的ExpressJS路由器

Node.js 使用带有子域的ExpressJS路由器,node.js,express,Node.js,Express,由于共享主机的情况,我被迫将所有传入的请求重定向到localhost上的非80端口,这是通过htaccess实现的。这会使HTTP主机头变为始终为localhost,而不管我尝试请求哪个子域。很简单,我找到了一个使用x-forwarded-host的解决方法,但这意味着我无法依赖NPM上当前可用的任何Express子域中间件包,因为它们都依赖于该主机头(据我所知) 所以我设法向路由器发送请求。但由于某些原因,我试图对我激活的特定子域的路由器进行的任何请求处理都不会被路由器接收,并直接传递到404

由于共享主机的情况,我被迫将所有传入的请求重定向到localhost上的非80端口,这是通过htaccess实现的。这会使HTTP主机头变为始终为localhost,而不管我尝试请求哪个子域。很简单,我找到了一个使用x-forwarded-host的解决方法,但这意味着我无法依赖NPM上当前可用的任何Express子域中间件包,因为它们都依赖于该主机头(据我所知)

所以我设法向路由器发送请求。但由于某些原因,我试图对我激活的特定子域的路由器进行的任何请求处理都不会被路由器接收,并直接传递到404处理程序

/index.js

const path=require('path');
常数fs=要求('fs');
const express=require('express');
常量app=express();
常数端口=30001;
const subdomainHosts=[];
fs.readdirSync('./routes/subdomain').filter(file=>file.endsWith('.js')).forEach(host=>{
subdomainHosts.push(host.split('.js')[0]);
});
const forwardSubdomain=require('./middleware/forwardSubdomain');
应用程序使用(转发子域(子域主机));
app.use(express.static(path.join(uu dirname,'public'));
应用程序使用((请求、恢复、下一步)=>{
返回res.status(404.sendFile)(path.join(process.cwd(),'public/404.html');
});
/middleware/forwardSubdomain.js

module.exports=(子域主机)=>{
返回(请求、恢复、下一步)=>{
让host=req.headers['x-forwarded-host']?req.headers['x-forwarded-host']:'';
host=host.split(':')[0]。split('.example.com')[0];
const isSubdomain=(主机和子域主机。包括(主机));
如果(发布域){
const subdomainRouter=require(`../routes/subdomain/${host}.js`);
返回子域路由器(req、res、next);
}
next();
};
};
/routes/subdomain/test.js

const path=require('path');
const express=require('express');
const router=express.router();
use(express.static(path.join(process.cwd(),'test'));
module.exports=路由器;
/test/
包含一个简单的hello world index.html。然而,尝试访问test.example.com给了我404

我很确定我错过了一些明显的东西,但我已经在这上面坐了太久了,所以我大声呼救