当我从节点快速提供我的角度 5 应用程序时,我遇到了这个问题作为快速静态服务索引.html当我访问 domain.com 但我访问时 domain.com/something 它工作正常,我可以提供帮助如何解决这个问题
app.use(express.static(path.join(__dirname, 'dist'))); //This line serves index.html how to deny it
app.use("/api", routes);
app.get('*', function(req, res) { //The reason it needs to be * so that it works with angular routes or it wont work
//This is never called when i visit domain.com. but it does when i visit domain.com/somthing
console.log("i was serverd");
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
提前致谢:)
找到解决方案
var options = {
index: false
}
app.use(express.static(path.join(__dirname, 'dist'), options));
索引:发送指定的目录索引文件。设置为 false 以禁用目录索引。
参考: http://expressjs.com/en/api.html
我已经为您的prooblem找到了解决方法
app.use('/',(req,res,next)=>{
if(req.path!='/')
next();
console.log('ii');
res.sendFile(path.join(__dirname,'dist/index.html'));
},express.static(path.join(__dirname, 'dist')));
app.get('*',(req,res,next)=>{
console.log('ii');
res.sendFile(path.join(__dirname,'dist/index.html'));
});
这将满足您的所有要求。但是通过这种方式,您必须在 2 条路由中编写相同的代码
将*
替换为 /
。
这应该在app.use(express.static
调用之前注册。(谢谢jfriend00(
前任:
app.get('/', function(req, res) { //see, no asterix
//This is never called when i visit domain.com. but it does when i visit domain.com/somthing
console.log("i was serverd");
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
app.use(express.static(path.join(__dirname, 'dist')));