简体   繁体   中英

express.static(__dirname+'/public') is not working

My app's directory structure:

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

And my coding:

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);

When use localhost:8888 , the stylesheet.js is loaded nicely. But when I use localhost:8888/article.html , the stylesheet does not load. I followed {{title}} works in article.html file But when I try to see the code of stylesheet, I see error text:

TypeError: Cannot read property 'title' of undefined

Why entry.title is undefined for stylesheet(except the index page)?

Change the href to /stylesheet.css . When you visit /article/.. the browser looks up /article/stylesheet.css because the href is (currently) a relative path in your article.html.

This doesn't seem related with the stylesheet.js rather with the function call in var entry = blogEngine.getBlogEntry(req.params.id);

It apparently is returning undefined then when it tries to read entry.title it throws that error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM