本文介绍了类型错误:无法在“WebAssembly"上执行“编译":响应 MIME 类型不正确.预期的“应用程序/wasm"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Chrome 上的 fetch api 加载 .wasm 文件,并使用 express 提供 html 文件.但是 chrome 不允许我加载文件:

I'm trying to load a .wasm file using the fetch api on Chrome , and serving a html file using express. But chrome does not let me load the file:

'Uncaught (in promise) TypeError: Failed to execute 'compile' on 'WebAssembly': 不正确的响应 MIME 类型.应为应用程序/wasm".

'Uncaught (in promise) TypeError: Failed to execute 'compile' on 'WebAssembly': Incorrect response MIME type. Expected 'application/wasm'.'

这是我的文件:

/public/index.html

/public/index.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <script type="text/javascript">
          WebAssembly.instantiateStreaming(fetch('http://localhost:3000/simple.wasm'))
      .then(obj => {
       console.log(obj.instance.exports.add(1, 2));  // "3"
      });
    </script>
  </body>
</html>

快递服务:

/index.js

const express = require('express')
express.static.mime.define({'application/wasm': ['wasm']})
var app = express();

app.use('/', express.static('public'));

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

我可以在提供 .wasm 文件时添加新的 mime 类型来表达吗?还是让chrome接受?我不知道如何解决它^^

Can i add a new mime type to express when serving a .wasm file?Or allow chrome to accept it?I dont have any idea for how to solve it ^^

参见:http://kripken.github.io/emscripten-站点/文档/编译/WebAssembly.html

Web server setup
To serve wasm in the most efficient way over the network, make sure your web server has the proper MIME time for .wasm files, which is application/wasm. That will allow streaming compilation, where the browser can start to compile code as it downloads.

In Apache, you can do this with

AddType application/wasm .wasm
Also make sure that gzip is enabled:

AddOutputFilterByType DEFLATE application/wasm

谢谢大家!

推荐答案

一种可能的解决方法是使用 instantiate() 而不是 instantiateStreaming(),因为前者没有不关心 MIME 类型(而后者 ).使用 instantiate():

One possible workaround is to use instantiate() instead of instantiateStreaming(), since the former doesn't care about MIME types (while the latter does). To use instantiate():

async function fetchAndInstantiate() {
    const response = await fetch("http://localhost:3000/simple.wasm");
    const buffer = await response.arrayBuffer();
    const obj = await WebAssembly.instantiate(buffer);
    console.log(obj.instance.exports.add(1, 2));  // "3"
}

这篇关于类型错误:无法在“WebAssembly"上执行“编译":响应 MIME 类型不正确.预期的“应用程序/wasm"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 04:43