我正在使用nodejs和webpack4,我正在尝试将main.js文件链接到index.html.我尝试了网络上所有可能的解决方案,它们似乎都不适合我。我是新手,欢迎提出建议,请让我知道我做错了什么。
这是我看到的错误日志:
GET http://localhost:3000/dist/main.js net::ERR_ABORTED
localhost/:1
Refused to execute script from 'http://localhost:3000/dist/main.js'
because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
public/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
</head>
<body>
<form action="/" method="POST" accept-charset="utf-8">
<input type="email" name="email" placeholder="Email">
<input type="submit" name="submit">
</form>
<script type="text/javascript" src="dist/main.js"> </script>
</body>
</html>
/app.js
const express = require('express');
const app = express();
const http = require('http');
//Middleware
app.use(express.static(__dirname + '/public' ));
app.post('/', function( req ,res){
res.send("Success");
});
app.listen(3000, function(){
console.log('Server running on port 3000');
});
文件结构
news_letter //Root directory
|_ dist
| |_ main.js
|_ public
| |_ index.html
|_ src
| |_ index.js
|_ app.js
main.js
文件位于公用文件夹中。
看起来您将main.js
文件放在dist/
文件夹中,index.html
文件放在public/
文件夹中。
但您只将app.js
文件中的一个目录设置为"静态文件目录">
app.use(express.static(__dirname + '/public' ));
HTML 中的每个路径都相对于公用文件夹中的路径。因此,将您的dist/
文件夹移动到public/
文件夹中,一切正常
文件结构
news_letter //Root directory
|_ public
| |_ dist
| | |_ main.js
| |_ index.html
|_ src
| |_ index.js
|_ app.js
就我而言,我还必须将中间件行更改为:
app.use('/public', express.static(__dirname + '/public' ));
而不是:
app.use(express.static(__dirname + '/public' ));
基于文档的原因是:
但是,您提供给 express.static 函数的路径相对于从中启动节点进程的目录。如果从另一个目录运行快速应用,则使用要服务的目录的绝对路径会更安全:
app.use('/static', express.static(path.join(__dirname, 'public')))
以下内容对我有用。
添加以下标题作为我案例中修复的中间件
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
next();
});