在Express net :: ERR_FILE_NOT_FOUND

时间:2020-05-14 07:45:00

标签: node.js express

我的文件夹结构是:

APP
 -public
   main.js
 -views
   index.html
 index.js

我正在尝试将静态文件提供给服务器,但无法正常工作。我的index.js文件中的代码为:

const express = require('express'),
      app     = express();

app.use(express.static(__dirname+'/public'));

我也尝试过使用path.join语法

在views文件夹的index.html文件中,我将src标记用作“ main.js”

<script type="text/javascript" src="main.js"></script>

我得到了错误net :: ERR_FILE_NOT_FOUND。 我还可以看到src所指路径是错误的。 它正在视图目录中查找main.js文件,而不是在公共目录中查找。

我看了其他答案。我从理论上了解语法,但无法找到我做错了

请在我的代码中指出问题。谢谢

1 个答案:

答案 0 :(得分:0)

这是一个可行的示例:

index.js

const express = require('express');
const path = require('path');
const app = express();
const port = 3000;

app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
  res.sendFile(path.resolve(__dirname, './views/index.html'));
});

app.listen(port, () => console.log(`server is listening on port ${port}`));

./public/main.js

window.onload = function() {
  console.log('onload');
};

./views/index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script type="text/javascript" src="main.js"></script>
  </head>
  <body>
    This is template
  </body>
</html>