javascript 配置 Express 为每个 url 发送 index.html,除了以 .css 和 .js 结尾的那些
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25498775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Configure Express to send index.html for every url EXCEPT those ending in .css and .js
提问by Tucker Connelly
I'm new to Express and I'm trying to set up a SPA where every url is handled by index.html (Backbone).
我是 Express 的新手,我正在尝试设置一个 SPA,其中每个 url 都由 index.html (Backbone) 处理。
I want every url to send down index.html, except /bundle.js and /style.css--or better yet, any url that would indicate a file (ending in .xyz)
我希望每个 url 都向下发送 index.html,除了 /bundle.js 和 /style.css——或者更好的是,任何表示文件的 url(以 .xyz 结尾)
I tried:
我试过:
app.get('*', function(req, res) {
res.sendfile(__dirname+'/public/index.html');
};
But that sent down bundle.js with the contents of index.html. How do I do this?
但是它发送了带有 index.html 内容的 bundle.js。我该怎么做呢?
回答by Kevin Reilly
I believe there may be two approaches to solve this goal with the first likely being preferable. If you can move bundle.js
and style.css
, place them as well as any other static files in the public
directory and use the following approach to statically serve all files out of public
:
我相信可能有两种方法来解决这个目标,第一种可能更可取。如果您可以移动bundle.js
和style.css
,请将它们以及任何其他静态文件放在public
目录中,并使用以下方法静态提供 中的所有文件public
:
app.use(express.static(__dirname + '/public'));
app.get('*', function(req, res){
res.sendfile(__dirname + '/public/index.html');
});
This approach is preferable because it will "just work" when you place new static files in the public
directory. You should then be able to access these static files at http://server:port/bundle.js(or appropriate child folder depending on your chosen hierarchy)
这种方法更可取,因为当您在public
目录中放置新的静态文件时它会“正常工作” 。然后,您应该能够在http://server:port/bundle.js(或相应的子文件夹,具体取决于您选择的层次结构)访问这些静态文件
Alternatively, you can leave the file structure as is and use the order in which the routes are defined to accomplish similar behavior, though it is not quite as flexible and is essentially statically defined:
或者,您可以保持文件结构不变,并使用定义路由的顺序来完成类似的行为,尽管它不太灵活并且基本上是静态定义的:
app.get('/bundle.js', function(req, res){
res.sendfile(__dirname + '/bundle.js');
});
app.get('/style.css', function(req, res){
res.sendfile(__dirname + '/style.css');
});
app.get('*', function(req, res){
res.sendfile(__dirname + '/public/index.html');
});