express.static(__ dirname +'/ public')不起作用
我的应用程序的目录结构:
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.title
是undefined
的样式表(索引页面除外)?
将href
更改为/stylesheet.css
。 当你访问/article/..
浏览器查找/article/stylesheet.css
因为href
是(当前)在你的article.html中的相对path。
这似乎与stylesheet.js
而不是与var entry = blogEngine.getBlogEntry(req.params.id);
的函数调用var entry = blogEngine.getBlogEntry(req.params.id);
它显然是返回undefined
然后当它试图读取entry.title
它会引发错误。