简体   繁体   English

Express:使用ejs时找不到静态文件

[英]Express: static files not found when using ejs

I want all my requests to be redirected to a index.ejs view, located in the Views folder. 我希望将所有请求重定向到位于Views文件夹中的index.ejs视图。 In my routes.js file, I've added this: 在我的routes.js文件中,我添加了以下内容:

  module.exports = function (app) {

  app.get('/', function(req, res) {
     res.render('index', {title: "TODO"})
 });
}

The index view contains all of page's markups as it will be a SPA, so I will dynamically swap views on the client-side. 索引视图将包含SPA的所有页面标记,因此我将在客户端动态交换视图。

The problem is that I references scripts located in the public folder and they are not found, I get a 404 : 问题是我引用了位于公共文件夹中的脚本,但找不到它们,我得到了404:

script src="public/app/app.js"></script>

I think it's because Express does not know how to server the file. 我认为这是因为Express不知道如何处理文件。 I've specified that everything in the public folder should be static files: 我已指定公用文件夹中的所有内容均应为静态文件:

   app.use(express.static(config.root + '/public'))  

Now if I don't use ejs template and if I use a index.html file in the public folder instead of a view, it works fine. 现在,如果我不使用ejs模板,并且在公用文件夹而不是视图中使用index.html文件,则可以正常工作。 I just have to do that instead: 我只需要这样做:

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

But I want to take advantage of ejs template for adding bundles to page instead of adding scripts one by one. 但是我想利用ejs模板将捆绑包添加到页面中,而不是一一添加脚本。

So what is wrong with my code ? 那么我的代码有什么问题呢? How can I solve that 404 on the javascript files ? 如何解决JavaScript文件上的404?

Got it. 得到它了。 The path to the script file was incorrect. 脚本文件的路径不正确。 It should be app/app.js instead of public/app/app.js 它应该是app / app.js而不是public / app / app.js

I think this is how the static middleware works. 我认为这就是静态中间件的工作方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM