Express - 无法提供静态文件(404错误)

5

我遇到了很多类似这样的问题,但看起来我没有做错什么。问题是我的静态文件无法加载。

文件夹结构:

/client
    index.html
    /assets
        /css
            main.css
/server
    app.js

app.js:

var assetsPath = path.join(__dirname, '../client/assets');
app.use(express.static('assetsPath'));

app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname, '../client/' + 'index.html'));
});

app.listen(PORT, function () {
    console.log('\nListening on port 8080!');
});

index.html

<link rel="stylesheet" href="/css/main.css">

然而,当在浏览器中加载页面时,http://localhost:8080/css/main.css 返回404错误。

是否有遗漏的内容?

谢谢!

PS:使用express ^4.13.4和node v5.10.1

2个回答

6

您在 express.static() 函数中拼写错误了。

var assetsPath = path.join(__dirname, '../client/assets');
app.use(express.static('assetsPath'));

应该是

var assetsPath = path.join(__dirname, '../client/assets');
app.use(express.static(assetsPath));

1
好的,这是那种时刻之一... - watt

3

express.static函数接受静态文件的路径,因此你可以使用以下代码来简化代码:

app.use(express.static(path.join(__dirname, '../client/assets')));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接