【问题标题】:I can't use EJS layout using res.render()我不能使用 res.render() 来使用 EJS 布局
【发布时间】:2014-12-24 18:50:54
【问题描述】:

我一直在尝试使用 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

【问题讨论】:

  • 显示视图的目录结构
  • 你好 Suraj,我可以克服这个问题。还是谢谢..

标签: node.js express ejs embedded-javascript


【解决方案1】:

Express 需要一个名为 'public' 的文件夹来检查资源。所以我把我的资源文件放到了一个“.../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>

【讨论】:

  • 嗨 efkan,我有一个问题。我可以创建一个名为 head.ejs 的文件来插入 layout.ejs 吗?其他类似 '/users/login' 的链接可以吗?我试过但它松散的css文件。它适用于 index.ejs,但使用 login.ejs 会丢失 css 文件
猜你喜欢
  • 1970-01-01
  • 2019-01-25
  • 2018-05-29
  • 2020-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-07
  • 2016-11-16
相关资源
最近更新 更多