配置Express为每个url发送index.html,EXCEPT以.css和.js结尾 [英] Configure Express to send index.html for every url EXCEPT those ending in .css and .js

查看:88
本文介绍了配置Express为每个url发送index.html,EXCEPT以.css和.js结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的,我正在尝试建立一个SPA,每个网址都由index.html(Backbone)处理。



我想要每一个url发送index.html,除了/bundle.js和/style.css--更好的是,任何指示文件的URL(以.xyz结尾)



<我试过:

  app.get('*',function(req,res){
res。 sendfile(__ dirname +'/ public / index.html');
};

但是发送包含index.html的bundle.js,我该怎么做?

解决方案

我相信可能有两个如果您可以移动 bundle.js style.css ,将它们以及任何其他静态文件放在 public 目录中,并使用以下方法将所有文件从 public

  app.use(express.static(__ dirname +'/ pub lic')); 

app.get('*',function(req,res){
res.sendfile(__ dirname +'/public/index.html');
});

这种方法是可取的,因为当您将新的静态文件放在 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');
});


I'm new to Express and I'm trying to set up a SPA where every url is handled by 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)

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?

解决方案

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:

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)

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

这篇关于配置Express为每个url发送index.html,EXCEPT以.css和.js结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆