2014-07-04 58 views
1

我的應用程序的目錄結構:express.static(__目錄名稱+ '/公共')沒有工作

app 
    -views 
    -index.html 
    -article.html 
    -public 
    -stylesheet.js 

而且我的編碼:

var express = require('express'); 
var app = express(); 
var hbs = require('hbs'); 
var blogEngine = require('./blog'); 
app.set('view engine', 'html'); 
app.engine('html', hbs.__express); 
app.use(express.json(), express.urlencoded()); 
app.use(express.static(__dirname+'/public')); 
app.get('/', function(req, res) { 
    res.render('index',{title:"My Blog", entries:blogEngine.getBlogEntries()}); 
}); 
app.get('/article/:id', function(req, res) { 
    var entry = blogEngine.getBlogEntry(req.params.id); 
    res.render('article',{title:entry.title, blog:entry}); 
}); 
app.listen(8888); 

使用時localhost:8888,該stylesheet.js是很好的加載。但是當我使用localhost:8888/article.html時,樣式表不加載。 我跟着article.html文件{{title}}作品但當我嘗試看看樣式表的代碼,我看到了錯誤的文字:

TypeError: Cannot read property 'title' of undefined 

爲什麼entry.titleundefined的樣式表(除了索引頁)?

+0

您的article.html的外觀如何? – mscdex

+0

<鏈路的rel = 「樣式表」 類型= 「文本/ CSS的」 href = 「stylesheet.css中」>

{{blog.title}}

發佈時間:{{blog.published} } {{blog.body}} – Rejaul

+0

非常感謝@mscdex。它正在處理'/ stylesheet.css' – Rejaul

回答

0

這似乎並不與stylesheet.js,而與函數調用var entry = blogEngine.getBlogEntry(req.params.id);

它顯然將返回undefined當它試圖讀取entry.title它拋出的錯誤有關。

+0

我將樣式表與index.html和article.html鏈接起來。如何加載stylesheet.js與article.html? – Rejaul

1

href更改爲/stylesheet.css。當您訪問/article/..時,瀏覽器查找/article/stylesheet.css,因爲href(當前)是您article.html中的相對路徑。