2017-07-30 28 views
0

我目前正在爲我的項目使用express和handlebars。這是我使用車把的第一次,我無法弄清楚如何正確地引用我的CSS和JS文件什麼是使用把手引用CSS和JS文件的正確方法?

的位置

我目前的項目結構如下圖所示

- test (root) 
    -views 
    -js 
     -some JS files 
    -css 
     -some css files 
    -layout 
     -main.handlebars 
    - servers.js (my server) 

所以我在主體並以下.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> 

而且裏面{{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> 

但是這給了Cannot GET 404 http://localhost:8000/views/js/index.js錯誤時,它看起來是該文件的正確位置。

在把手中引用js和css文件的正確方法是什麼?

回答

0

您應該創建公用目錄,並且在服務器中可以提供靜態文件,如圖像,CSS文件和JavaScript文件,請使用Express中的express.static內置中間件功能。

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

enter image description here

現在,你可以加載在公共目錄下的文件:

<!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> 
+0

是...我很愚蠢 – forJ

相關問題