首页 > 解决方案 > 在 express net::ERR_FILE_NOT_FOUND 中提供静态文件

问题描述

我的文件夹结构是:

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 语法

在视图文件夹中的 index.html 文件中,我使用 src 标记作为“main.js”

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

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

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

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

标签: node.jsexpress

解决方案


这是一个工作示例:

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>

推荐阅读