【发布时间】:2020-01-25 00:53:15
【问题描述】:
当我尝试使用非常简单的应用程序运行本地节点服务器时收到以下错误消息(请参阅下面的代码)。
由于不允许的 MIME 类型(“text/html”),从“http://localhost:8080/importing.js”加载模块被阻止。
我是节点和 ES6 模块的新手,所以我不太了解问题的细节。根据这个URL,必须为模块显式地提供 mime 类型的“应用程序/javascript”。但是我如何在下面的示例中实现这一点?
index.html
<!DOCTYPE html>
<html>
<head>
<script src="./importing.js" type="module"></script>
<meta charset="utf-8">
</head>
<body>
</body>
</html>
server.js
var http = require('http');
var fs = require('fs');
const PORT=8080;
fs.readFile('./index.html', function (err, html) {
if (err) throw err;
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(PORT);
});
importing.js
import {a} from './exporting.js';
console.log(a);
exporting.js
export const a = 'Constant a';
我用 CMD 启动服务器
node server.js
【问题讨论】:
-
如果您的问题得到解决,请接受答案。这也会对其他人有所帮助。
标签: javascript node.js mime-types es6-modules