繁体   English   中英

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

[英]Express - can't serve static files (404 error)

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

资料夹结构:

/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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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