繁体   English   中英

加载模块脚本失败:服务器响应非 JavaScript MIME 类型“”

[英]Failed to load module script: The server responded with a non-JavaScript MIME type of ""

我有一个带有模块的 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>

... 模块内容是 ...

export class HelloWorld extends HTMLElement {
    get color () {
        return this.getAttribute('color') || 'gray'
    }

    set color (value) {
        this.setAttribute('color', value)
    }

    connectedCallback() {
        window.requestAnimationFrame(() => {
            const div = document.createElement('div')
            div.textContent = 'Hello World!!!'
            div.style.color = this.color
            this.appendChild(div)
        });
    }
}

我使用php -S localhost:8888 -t .运行 PHP 服务器php -S localhost:8888 -t . 一切正常:

在此处输入图片说明

相反,...如果我在./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 类型检查。

为什么? 我可以修吗? 如何?

您可以发送正确的内容类型 (text/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')

索引.html

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

主文件

document.getElementById('junk').innerHTML = 'loading ok'

请参阅故障排除

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

重命名文件以再次使用.js扩展名,您的 HTTP 服务器将为其发送正确的 Content-Type。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM