WebAssembly InstantiateStreaming 错误的 MIME 类型

新手上路,请多包涵

我正在尝试使本教程(此处: https ://www.hellorust.com/demos/add/index.html)正常工作,但似乎无论我做什么,我都无法使 WebAssembly MDN 保留功能正常工作.

因此,我按照上面链接上的说明进行了操作,得到了一个 add.wasm 文件。据我所知,这应该相当简单并且应该有效。经过一番挖掘后,我发现最新的 WebAssembly 模块用于实例化流 - 可以在此处找到相关文档:( https://developer.mozilla.org/en-US/docs/WebAssembly/Using_the_JavaScript_API )。

MDN 示例说要执行以下操作:

 var importObject = {
  imports: { imported_func: arg => console.log(arg) }
};

然后

WebAssembly.instantiateStreaming(fetch('simple.wasm'), importObject)
.then(obj => obj.instance.exports.exported_func());

根据 MDN,importObject 用于解包嵌套参数。很奇怪,但还可以。

为了尽可能简单,我将 add.wasm 文件和 js 文件放在同一目录中,然后执行以下操作( 注意:我使用的是 Vue.js ,但对于任何熟悉 SPA 之类的库的人来说,这应该是相似的):

 window.WebAssembly.instantiateStreaming(fetch('./add.wasm', {
  headers: {
    "Content-Type": "application/wasm",
  },
}), importObject)
.then(obj => {
  console.log('inside return obj from WebAssembly initiateStreaming')
  obj => obj.instance.exports.exported_func()
})
.catch(error=>{
  console.log('there was some error; ', error)
});

我得到的错误是:

 there was some error;  TypeError: "Response has unsupported MIME type"

I’ve tried not adding the header to the fetch request, using fetch(add.wasm) , dropping the window. , dropping the importObject entirely and simple logging obj 安慰。似乎没有任何效果。

可能是我必须以某种方式将 application/wasm 字段添加到 webpack,如果它没有得到广泛支持,但我不确定并且我没有在网上看到任何示例。

有谁知道如何让它工作?

编辑:

有人建议,因为这是一个获取请求,所以它必须从后端服务器发出请求。这对我来说很有意义,所以我做了以下事情:

     WebAssembly.instantiateStreaming(fetch('http://localhost:8000/files/add.wasm'), importObject)
    .then(obj => {
      console.log('inside return obj from WebAssembly initiateStreaming')
      obj => obj.instance.exports.exported_func()
    })
    .catch(error=>{
      console.log('there was some error; ', error)
    });

其中 http://localhost:8000/files/{someFile} 是为我的文件提供服务的后端路由(当然,我确保将 add.wasm 放入)。不幸的是,我得到了同样的错误(即 unrecognized MIME type ),我不确定为什么。

原文由 Peter Weyand 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 855
1 个回答

考虑到您无法更改服务器以出于任何原因正确返回 application/wasm .wasm 文件请求,您可以通过更改实例化 WebAssembly 模块的方式来解决此问题。而不是这样做:

 WebAssembly.instantiateStreaming(fetch("./add.wasm")).then(obj => /* ... */)

做这个:

 const response = await fetch("add.wasm");
const buffer = await response.arrayBuffer();
const obj = await WebAssembly.instantiate(buffer);
obj.instance.exports.exported_func();

或等效使用 then() 如果你不能使用 async/await

实际上,我的解决方法是避免调用 instantiateStreaming() ,它必须在继续之前检查服务器返回的 MIME 类型(根据 本规范)。相反,我调用 instantiate() 传递 ArrayBuffer 并完全避免检查。

原文由 Lucio Paiva 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题