当我在生产服务器上运行捆绑的 React 应用程序时,它找不到我的图像文件,我不确定为什么。我相当确定这与我的 Node 快速配置和/或我的 .ejs
模板文件有关。
server.js
var express = require('express')
var app = express();
const path = require('path');
app.use('/static', express.static(__dirname + '/static'));
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.get('*', function (req, res) {
res.render("index");
});
const port = process.env.PORT || 3000;
const env = process.env.NODE_ENV || 'production';
app.listen(port, err => {
if (err) {
return console.error(err);
}
console.info(`Server running on http://localhost:${port} [${env}]`);
});
index.ejs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Production Server</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="https://fonts.googleapis.com/css?family=BenchNine" rel="stylesheet">
<link rel="stylesheet" href="../static/css/main.css">
</head>
<body>
<div id="root"></div>
<script src="../static/js/bundle.js"></script>
</body>
</html>
我的CSS样式表在模板文件中被调用,所有JS都被捆绑到bundle.js
中,并在script标签中引用。但我不确定如何让我的应用程序识别 /img
文件夹,因为目前它还不能识别。
这是我的文件结构:
- static
- css
- main.css
- js
- bundle.js
- img (contains all image files)
但是,当我运行应用程序并在 Chrome 控制台中打开“源”时,未提供/img 文件。
我认为这一行表明 Express 提供 /static
文件夹中的所有内容...
app.use('/static', express.static(__dirname + '/static'));
...但只有三分之二的文件正在被提供。
如果有人能告诉我我的设置哪里出了问题,我将不胜感激。
提前致谢。
最佳答案
DevTools 中的源选项卡将仅显示您的案例中浏览器正在使用的内容index.ejs,它仅使用 .js 和 .css 文件
在 Index.ejs 中您正在加载
<script src="../static/js/bundle.js"></script>
和<link rel="stylesheet" href="../static/css/main.css">
这意味着中间件 app.use('/static', express.static(__dirname + '/static'));
将检查是否 /js/bundle.js
和/css/main.css
是否存在于静态文件夹中,如果是,它将为它们提供服务,如果没有,则会给出找不到文件或文件夹。
这意味着无论您从index.ejs 中的静态文件夹加载或在index.ejs 中使用,内容和文件都将出现在源选项卡中。 尝试从静态文件夹中的index.ejs中添加图像,然后查看源选项卡
或删除 <script src="../static/js/bundle.js"></script>
并查看源选项卡,您将看不到 JS 文件夹,因为它没有被 index.ejs 使用
Always reload the server
关于node.js - Node Express 服务器不提供图像文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41523917/