该问题的核心原因是 服务器没有正确返回 application/wasm
的 MIME 类型。
- 最推荐 的方法是在服务器端配置
.wasm
文件的 MIME 类型。 - 如果无法修改服务器,可以尝试 手动 fetch + 设置
Content-Type
。
这个错误的原因是浏览器在加载 .wasm
文件时,服务器返回的 MIME 类型(Content-Type)不正确,导致 WebAssembly 模块无法正确编译。
错误产生原因
WebAssembly(Wasm)是一种高性能的二进制格式,浏览器在加载 .wasm
文件时,要求服务器 必须返回 application/wasm
的 MIME 类型。
但很多情况下,服务器默认 不会 为 .wasm
文件设置正确的 MIME 类型,而是返回 application/octet-stream
或 text/plain
,从而导致这个错误。
如何解决
vite 配置
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import {viteStaticCopy} from "vite-plugin-static-copy";
export default defineConfig({
plugins: [
react(),
// 只有线上会用
viteStaticCopy({
targets: [
{ src: 'node_modules/onnxruntime-web/dist/*.wasm', dest: 'ort' },
],
}),
// 开发环境中间件
{
name: 'force-wasm-mime',
configureServer(server) {
server.middlewares.use((req, res, next) => {
if (req.url?.endsWith('.wasm')) {
res.setHeader('Content-Type', 'application/wasm')
}
next()
})
},
}
],
server: {
headers: {
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Embedder-Policy': 'require-corp',
},
middlewareMode: false,
},
})
Express 配置
app.use("/wasm", express.static("wasm_folder", {
setHeaders: (res) => {
res.set("Content-Type", "application/wasm");
}
}));
Nginx 配置(nginx.conf)
types {
application/wasm wasm;
}
临时解决方案(手动 fetch): 如果 无法修改服务器配置,可以在 JavaScript 加载 Wasm 时 手动指定 MIME 类型:
const response = await fetch("module.wasm", {
headers: { "Content-Type": "application/wasm" }
});
const wasmBuffer = await response.arrayBuffer();
const module = await WebAssembly.compile(wasmBuffer);
ort配置无法加载问题
import * as ort from 'onnxruntime-web'
// 获取当前页面的基础 URL,用于拼接资源路径
const baseAbs = new URL(import.meta.env.BASE_URL, window.location.href)
// 设置 ORT 的 wasm 路径,确保模型推理时能正确加载 wasm 文件
ort.env.wasm.wasmPaths = '/ort/';
// 构造 JSEP 相关 wasm 和 mjs 文件的绝对路径
const mjsUrl = new URL('ort/ort-wasm-simd-threaded.jsep.mjs', baseAbs).toString()
const wasmUrl = new URL('ort/ort-wasm-simd-threaded.jsep.wasm', baseAbs).toString()
// 指定 ORT 查找 wasm 资源的路径,避免 public/ort 路径报错
ort.env.wasm.wasmPaths = {
mjs: mjsUrl,
wasm: wasmUrl,
}