【问题标题】:Setting up the directory management in Express Handlebars在 Express Handlebars 中设置目录管理
【发布时间】:2017-11-22 14:04:50
【问题描述】:

我使用 NodeJsExpressHandlebars

我的服务器文件app.js

const express = require('express');
const exphbs  = require('express-handlebars');

const app = express();

app.engine('handlebars', exphbs({defaultLayout: 'index'}));
app.set('view engine', 'handlebars');

app.get('/start', function (req, res) {
  res.render('start'); // render the "start" template
});

app.listen(8888, function () {
  console.log('Server running on port 8888');
});

所以当通过路线localhost:8888/start时应该有我的index.handlebars

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Foo</title>
</head>

<link href="../../CSS/requirements.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

<body>

  <p>TEST - This is on all pages</p>

{{{body}}}

</body>
</html>

以及要加载的模板 (start.handlebars)

<script src="../Client/start.js"></script>

<p>Template 1 is active</p>

我的目录结构

运行服务器时,我的路由加载正常,但问题是浏览器无法找到脚本和 css 文件。

我检查了我的路径,但我认为它们可能是正确的。我错了吗?

【问题讨论】:

    标签: javascript node.js express handlebars.js


    【解决方案1】:

    您必须在您的express 应用程序中设置static 文件夹。添加以下中间件

    app.use(express.static(path.join(__dirname, 'public')));
    

    紧接着

    app.set('view engine', 'handlebars');
    

    在您的根级别创建一个公用文件夹,并将您的 ClientCSS 文件夹移动到该 public 文件夹中。

    参考:Link

    【讨论】:

      猜你喜欢
      • 2018-11-03
      • 1970-01-01
      • 1970-01-01
      • 2019-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多