我刚刚构建了一个 Webpack 项目:
static/ // where I have the js and css file
index.html // the main file
并将其放置在 Express 设置中的 public/
文件夹中:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.sendfile('public/index.html')
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
但是我收到这些错误:
http://localhost:3000/static/app.79c874fce37c5d0a32117271eb04a7f8.css
http://localhost:3000/static/app.57fd4b2335b940c7b8d1.js 404 (Not Found)
这是index.html
的内容:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<title>istaging-viewer</title>
<link href=/static/app.79c874fce37c5d0a32117271eb04a7f8.css rel=stylesheet>
</head>
<body>
<div id=app>
<script src=/static/app.57fd4b2335b940c7b8d1.js></script>
</div>
</body>
</html>
(这些文件存在于 /static/
目录中)。
我应该如何更改 Express 代码以便 Express 可以找到这些文件?
编辑:我尝试过这个...
app.get('/', function (req, res) {
res.sendfile('static/index.html')
});
...但我仍然收到此错误:
GET http://localhost:3000/static/app.79c874fce37c5d0a32117271eb04a7f8.css
localhost/:1 GET http://localhost:3000/static/app.57fd4b2335b940c7b8d1.js 404 (Not Found)
编辑2:
我尝试用这个来提供静态文件:
app.use(express.static('static'));
我仍然遇到同样的错误:
GET http://localhost:3000/static/app.79c874fce37c5d0a32117271eb04a7f8.css
localhost/:1 GET http://localhost:3000/static/app.57fd4b2335b940c7b8d1.js 404 (Not Found)
最佳答案
只要你的app/main js文件与你的index.html在同一个文件夹中,然后更改
app.get('/', function (req, res) {
res.sendfile('public/index.html')
});
至
app.get('/', function (req, res) {
res.sendfile('index.html')
});
但是,理想情况下,您的文件结构应类似于:
app.js
static/
index.html
js/
css/
img/
这样,您就可以这样引用它
app.get('/', function (req, res) {
res.sendfile('static/index.html')
});
关于javascript - 以下公共(public)目录设置有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35984745/