express.static(__ dirname +'/ public')不起作用

时间:2014-07-04 19:11:08

标签: node.js express

我的应用程序的目录结构:

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时,样式表.js可以很好地加载。但是当我使用localhost:8888/article.html时,样式表无法加载。 我跟着{{title}}article.html文件中工作但是当我尝试查看样式表的代码时,我看到错误文本:

TypeError: Cannot read property 'title' of undefined

为什么entry.title为样式表undefined(索引页除外)?

2 个答案:

答案 0 :(得分:1)

href更改为/stylesheet.css。当您访问/article/..时,浏览器会查找/article/stylesheet.css,因为href(当前)是您文章中的相对路径。

答案 1 :(得分:0)

这似乎与stylesheet.js无关,而与var entry = blogEngine.getBlogEntry(req.params.id);

中的函数调用相关

显然它正在返回undefined然后当它尝试读取entry.title时会抛出该错误。