以下公共目录设置有什么问题?

时间:2016-03-14 10:16:12

标签: javascript node.js express

我刚建了一个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')
});

enter image description here

...但我仍然收到此错误:

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)

1 个答案:

答案 0 :(得分:2)

只要您的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')
});