如何修复“text/html”的MIME类型?

问题描述 投票:0回答:1

我想通过html和js制作docx文件,我也使用Docx库和Filesaver

但是我遇到了下一个错误:

无法加载模块脚本:需要 JavaScript 模块脚本,但服务器以 MIME 类型“text/html”进行响应。根据 HTML 规范对模块脚本强制执行严格的 MIME 类型检查。

我正在使用下一个 html 代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=chrome">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <nav></nav>
    <section>
        <button>
            <input type="file" id="input">
            <button style="display: block; margin-top: 5em;" id="generate">Create custom DOCX type from XL document</button>
        </button>
    </section>
    <footer></footer>
    <script type="module" src="js/script.js"></script>
</body>
</html>

和js:

import { Document, Packer } from "../node_modules/docx/build/index"
import { saveAs } from "../node_modules/file-saver/dist/FileSaver"

document.getElementById("generate").addEventListener(
    "click",
    function (event) {
        generateWordDocument(event)
    },
    false
)
function generateWordDocument(event) {
    event.preventDefault()
    // Create a new instance of Document for the docx module
    let doc = new Document()
    // Call saveDocumentToFile with the document instance and a filename
    saveDocumentToFile(doc, "New Document.docx")
}
function saveDocumentToFile(doc, fileName) {
    // Create new instance of Packer for the docx module
    const packer = new Packer()
    // Create a mime type that will associate the new file with Microsoft Word
    const mimeType =
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    // Create a Blob containing the Document instance and the mimeType
    packer.toBlob(doc).then(blob => {
        const docblob = blob.slice(0, blob.size, mimeType)
        // Save the file using saveAs from the file-saver package
        saveAs(docblob, fileName)
    })
}

const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
let fileList = inputElement.files
function handleFiles() {
    fileList = this.files; /* now you can work with the file list */
    console.log(fileList[0].name)
}

我接下来下载 docx 和文件保护程序:

npm 安装 docx

npm 安装文件保护程序

和http服务器

我正在使用 http-server 来测试我的代码

http 服务器-c-1

如何修复这段代码中text/html的MIME类型?

我尝试更改 docx 和文件保护程序的路径 喜欢 “../package.json/docx” “文档” “../node_modules/docx” 等等,但没有用 我还尝试在 vscode 中使用另一台服务器作为 http 服务器和实时服务器,但没有任何效果

javascript html node.js module node-modules
1个回答
1
投票

该错误与您的 DOCX 内容无关。它抱怨请求模块时获得的

js/script.js
响应中的 MIME 类型。显然,
http-server
返回
text/html
作为其内容类型,这是不允许的;它必须是有效的 JavaScript MIME 类型(例如
text/javascript
,尽管
application/javascript
和其他一些类型也可以)。

http-server
文档说您可以传递
--mimetypes
来指定包含要使用的MIME类型的
.types
文件,告诉它使用
text/javascript
作为MIME类型(可能带有
charset
),尽管它不会告诉您该文件的格式应该是什么(您可能可以从源代码中找出它)。或者您可以考虑使用另一个自动处理此问题的服务器。

© www.soinside.com 2019 - 2024. All rights reserved.