Tuc*_*lly 15 javascript node.js express
我是Express的新手,我正在尝试建立一个SPA,其中每个URL都由index.html(Backbone)处理.
我希望每个url都发送index.html,除了/bundle.js和/ style.css--或者更好的是,任何指示文件的url(以.xyz结尾)
我试过了:
app.get('*', function(req, res) {
res.sendfile(__dirname+'/public/index.html');
};
Run Code Online (Sandbox Code Playgroud)
但是发送了带有index.html内容的bundle.js.我该怎么做呢?
Kev*_*lly 23
我相信可能有两种方法可以解决这个目标,第一种可能更可取.如果你可以移动bundle.js和style.css,将它们以及在任何其他静态文件public目录,并使用下面的方法来静态地为所有的文件出来的public:
app.use(express.static(__dirname + '/public'));
app.get('*', function(req, res){
res.sendfile(__dirname + '/public/index.html');
});
Run Code Online (Sandbox Code Playgroud)
这种方法更可取,因为当您将新的静态文件放在public目录中时它将"正常工作" .然后,您应该能够访问http:// server:port/bundle.js(或根据您选择的层次结构的相应子文件夹)访问这些静态文件
或者,您可以保留文件结构,并使用定义路由的顺序来完成类似的行为,尽管它不是那么灵活,并且基本上是静态定义的:
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');
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16799 次 |
| 最近记录: |