javascript - 以下公共(public)目录设置有什么问题?

标签 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)

最佳答案

只要你的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/

相关文章:

javascript - 仅在 IE11 中首次单击时画廊灯箱不插入图像

javascript - 如何在jQuery中读取xml文件内容并显示在html元素中?

javascript - 使用传递的 MongoDB 查询定位数组中的第一个对象

javascript - [React.js]尝试导入错误: './registerServiceWorker' does not contain a default export (imported as 'registerServiceWorker' )

node.js - 如何在 Express js 单元测试中使用 sinon js

node.js - 如何清理 Nodejs (heroku + redis) 中的所有 session ?

node.js - 更新包含多个字段的文档

javascript - crossfilter.js 中的补集?

javascript - 如何在 azure-mobile-apps-js-client 中使用 substringof

javascript - Module.exports 函数为变量返回 'undefined'