未能加载模块脚本:服务器响应的非JavaScript MIME类型为&引用;

未能加载模块脚本:服务器响应的非JavaScript MIME类型为&引用;,javascript,Javascript,我有这个html页面与一个模块 <html> <body> <hello-world color="blue" /> <hello-world color="red" /> <hello-world /> <script type="module"> import { HelloWorld } from './HelloWorld

我有这个html页面与一个模块

<html>
    <body>
        <hello-world color="blue" />
        <hello-world color="red" />
        <hello-world />
        <script type="module">
            import { HelloWorld } from './HelloWorld.js'
            window.customElements.define('hello-world', HelloWorld)
        </script>
    </body>
</html>
我使用
PHP-S localhost:8888-t运行PHP服务器。
一切正常:

相反。。。如果我将模块移动到
/main.mjs
文件中并包含内容

import { HelloWorld } from './HelloWorld.js'
window.customElements.define('hello-world', HelloWorld)
。。。正在更改中的html部分

<html>
    <body>
        <hello-world color="blue" />
        <hello-world color="red" />
        <hello-world />
        <script type="module" src="main.mjs"></script>
    </body>
</html>

。。。我得到以下错误:

加载模块脚本失败:服务器响应的非JavaScript MIME类型为“”。根据HTML规范,对模块脚本执行严格的MIME类型检查


为什么??我可以修一下吗?如何发送?

您可以发送适当的内容类型(文本/javascript)来指定您正在发送js文件

节点中具有基本服务器的示例:

const http = require('http');
const fs = require('fs')
const requestListener = function (req, res) {
  f = req.url === '/' ? 'index.html' : 'main.mjs'

  // commenting that block will give an empty mime type and module will not be loaded
  if (f === 'main.mjs') {
    res.setHeader('Content-type', 'text/javascript')
  }
  res.writeHead(200)
  return fs.createReadStream(f).pipe(res)
}

const server = http.createServer(requestListener);
server.listen(8080);
console.log('listening: http://localhost:8080')
index.html

<!DOCTYPE html>
<html>
<body>
  <div id="junk">loading failed</div>
  <script type="module" src="main.mjs"></script>
</body>
</html>

请参见

您可以发送适当的内容类型(文本/javascript)来指定您正在发送js文件

节点中具有基本服务器的示例:

const http = require('http');
const fs = require('fs')
const requestListener = function (req, res) {
  f = req.url === '/' ? 'index.html' : 'main.mjs'

  // commenting that block will give an empty mime type and module will not be loaded
  if (f === 'main.mjs') {
    res.setHeader('Content-type', 'text/javascript')
  }
  res.writeHead(200)
  return fs.createReadStream(f).pipe(res)
}

const server = http.createServer(requestListener);
server.listen(8080);
console.log('listening: http://localhost:8080')
index.html

<!DOCTYPE html>
<html>
<body>
  <div id="junk">loading failed</div>
  <script type="module" src="main.mjs"></script>
</body>
</html>

请参见PHP的简单内置服务器没有为
.mjs
文件注册MIME类型。它不是一个常见的扩展,通常只用于Node.js中的ES6模块(由于使用了该扩展,因此不再需要)


将文件重命名为具有
.js
扩展名,您的HTTP服务器将为其发送正确的内容类型。

PHP的简单内置服务器没有为
.mjs
文件注册MIME类型。它不是一个常见的扩展,通常只用于Node.js中的ES6模块(由于使用了该扩展,因此不再需要)


将文件重命名为具有
.js
扩展名,您的HTTP服务器将为其发送正确的内容类型。

在node.js旁边,还有jasmine需要.mjs文件来支持ES6模块。因此,如果您想在多个用例中使用这些文件,重命名可能不是一个选项……在node.js旁边,还有一个jasmine需要.mjs文件来支持ES6模块。因此,如果您想在多个用例中使用这些文件,重命名可能不是一个选项。。。