用车把引用CSS和JS文件的正确方法是什么?

for*_*orJ 6 html javascript css node.js handlebars.js

我目前在为我的项目使用快递和车把。这是我第一次使用把手,我无法弄清楚如何正确引用CSS和JS文件的位置

我当前的项目结构如下

- test (root)
  -views
    -js
      -some JS files
    -css
      -some css files
    -layout
      -main.handlebars
  - servers.js (my server)
Run Code Online (Sandbox Code Playgroud)

所以我在main.handlebars布局文件中进行了跟踪

<!Doctype html>
<html>
<head>
    <title></title>
    {{#each css}}
        <link rel="stylesheet" href="../css/{{this}}">
    {{/each}}
</head>
<body>
    {{{body}}}
    {{#each js}}
        <script src="../js/{{this}}"></script>
    {{/each}}
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

在内部{{this}},index.css用于css,index.js用于js。

但这给了Cannot GET 404 http://localhost:8000/js/index.js错误。所以我想也许车把是从根源上看的。所以我尝试了

<!Doctype html>
<html>
<head>
    <title></title>
    {{#each css}}
        <link rel="stylesheet" href="views/css/{{this}}">
    {{/each}}
</head>
<body>
    {{{body}}}
    {{#each js}}
        <script src="views/js/{{this}}"></script>
    {{/each}}
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

但这Cannot GET 404 http://localhost:8000/views/js/index.js在看起来正确的文件位置时产生了错误。

在车把中引用js和CSS文件的正确方法是什么?

Bur*_*rdy 7

您应该创建公共目录,并在服务器中可以提供静态文件(例如图像,CSS文件和JavaScript文件),请使用Express中内置的express.static内置中间件功能。

app.use(express.static(path.join(__dirname, '/public'));
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

现在,您可以加载公共目录中的文件:

<!Doctype html>
<html>
<head>
    <title></title>
    {{#each css}}
        <link rel="stylesheet" href="/css/{{this}}">
    {{/each}}
</head>
<body>
    {{{body}}}
    {{#each js}}
        <script src="/js/{{this}}"></script>
    {{/each}}
</body>
</html>
Run Code Online (Sandbox Code Playgroud)