node.js - 在 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 文件,而不是在公共目录中查找。
我看过其他答案。我从理论上理解语法,但无法找到我做错了什么
请在我的代码中指出问题。谢谢
解决方案
这是一个工作示例:
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>
推荐阅读
- vue.js - 如何在 vuetify 表的标题之一中创建下拉选择
- sql - 如何使用 SQL 找到具有预定义最小间隙大小的所有“间隙”?
- python - 为什么 Selenium Chromedriver 快捷方式不起作用?
- python - Django Rest Framework - 如何从上传的视频创建 GIF 文件
- php - Symfony - 生成新 APP_SECRET 的终端命令
- javascript - 在我的 javascript 计算器中添加“退格”和“删除”键盘输入
- python - 在节点集中指定的节点处提取应变 [Abaqus python odb 访问]
- spring - 使用Java lambda parallelStream时RabbitMQ Spring“无法确定查找键的目标ConnectionFactory”
- python - Tensorflow:避免每次运行都下载 Inception V3
- javascript - 全局上下文中的 Javascript this 不起作用,或者看起来像 console.log 工作但使用 ref 不起作用