net::ERR_ABORTED 404(未找到)加载外部js脚本时出错


import express, { Express, Request, Response } from 'express';
const path = require("path");
import dotenv from 'dotenv';
dotenv.config();
const PORT = process.env.PORT || 5000;
const app = express();
app.use(express.static(path.join(__dirname, '../public')));
app.use(express.static(path.join(__dirname, '../public/css')));
app.use(express.static(__dirname));  
app.use(express.static(path.join(__dirname, '../public/img')));                  
app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'ejs')
app.get('', (req: Request, res: Response) => {
res.render('index.ejs', {text: 'This'});
});
app.listen(PORT, () => console.log(`Running on ${PORT} ⚡`));

目前,我在index.js页面上有这样的设置,我的文件系统是这样设置的

文件系统

我正在尝试将一个按钮链接到一个外部脚本,并且已经这样做了

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="css/main.css">
<script src="../dist/button.js"></script>
</head>
<body>
<div>
<button id="test">click</button>
</div>
</body>
</html>

index.ejs

const myButton = document.getElementById("test"); 
myButton!.addEventListener("click", () => {
});

按钮.js

我收到以下错误GET http://localhost:5000/dist/button.js net::ERR_ABORTED 404 (Not Found)

我试着改变express静态路径,并试图调整过滤系统,但到目前为止,这些都没有奏效,我仍在努力找出问题所在。

我遇到了同样的问题,主要问题是文件夹结构中的内容:Public应该在srcdir中而不是这个(你有(:

- public
- script.js
- ingex.html
- src
- index.js
...

你必须使用这个

- src
- index.js
- public
- script.js
- ingex.html
...

当然,我们在src/index.js中的快速配置中需要这一行

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

最后是html标签:

<script src="public/script.js"></script>

最新更新