0

我一直在尝试使用 express-ejs-layouts 模块。当我尝试第二条路线时,浏览器会在我的第二条 EJS 文件下找到我的 JS 和 CSS 资源文件——这是我写到第二条路线函数中的。

我应该怎么办?

我的布局在我的第一个路由过程中正确显示,如下所示。

我的第一条路线;

app.get('/', function(req, res) {
        res.render('home/index');
});

我的 layout.ejs 文件;

<!DOCTYPE html>
<html lang="tr">
<head>
    <link rel="stylesheet" href="bootstrap/css/bootstrap.css">
    <link rel="stylesheet" href="css/styles.css">    
</head>
<body>

    <% include navbar %>

    <%- body %> 

    <script src="js/jquery.js"></script>
    <script src="bootstrap/js/bootstrap.js"></script>

</body>
</html>

到目前为止一切都很好。我的资源文件(css 和 js)已链接,我可以正确地看到我的home/index.ejs。然后我尝试我的第二条路线,如下所示;

我的第二条路线;

app.get('/user/:id', function(req, res) {
     res.render('user/index');
});

我的浏览器控制台出现以下错误;

Failed to load resource: the server responded with a status of 404
(Not Found) http://localhost:1337/user/bootstrap/css/bootstrap.css

Failed to load resource: the server responded with a status of 404
(Not Found) http://localhost:1337/user/css/styles.css

Failed to load resource: the server responded with a status of 404
(Not Found) http://localhost:1337/user/js/jquery.js

Failed to load resource: the server responded with a status of 404
(Not Found) http://localhost:1337/user/bootstrap/js/bootstrap.js
4

1 回答 1

0

Express 需要一个“公共”命名文件夹来检查资源。所以我把我的资源文件放到了一个“.../public/”文件夹中,重写了 src 链接,我成功了。

我已经定义了一个新的静态路径;

app.use(express.static(__dirname + '/public'));

然后我更改了我的新 layout.ejs 文件,如下所示;

<!DOCTYPE html>
<html lang="tr">
<head>
    <link rel="stylesheet" href="/css/bootstrap.css">
    <link rel="stylesheet" href="/css/styles.css">    
</head>
<body>

    <% include navbar %>

    <%- body %> 

    <script src="/js/jquery.js"></script>
    <script src="/js/bootstrap.js"></script>

</body>
</html>
于 2014-12-24T10:50:54.873 回答