简体   繁体   中英

Unable to serve stylesheets in Node.js app

I am learning Node.js and Express (version 4.11). Currently, I am trying to create a basic web app that uses a stylesheet. In an attempt to do this, I have the following HTML:

<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="Description">
    <meta charset="UTF-8">

    <link rel="stylesheet" type="text/css" href="/public/fonts/icomoon.css" />
    <link rel="stylesheet" type="text/css" href="/public/css/style.css" />
</head>
<body>
  <h1 class="title">Test</h1>
</body>
</html>

When this HTML is loaded, I get 404 errors for my icomoon.css file and my style.css file. I'm confused, because I've followed the other similar post on SO. My server.js file looks like the following:

var express = require('express');                   // routing-engne
var expressHbs = require('express-handlebars');     // view-engine

// Setup the app to use Handlebars as the view engine
var app = express();
app.engine('hbs', expressHbs({extname:'hbs', defaultLayout:'layout.hbs'}));
app.set('view engine', 'hbs');

// Add support for static files (css, fonts, images, etc.)
app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res) {
    var viewModel = {};
    res.render('/index', viewModel);
});

// Start the app on port 3000
app.listen(3000);
console.log('Ready!');

I thought the line written as app.use(express.static ... would serve up my static files. However, it is not. How do I serve up my .css files?

Thank you!

用这个:

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

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