从 NestJs 后端加载 WebAssembly 文件时出错



我正在尝试将WebAssembly文件加载到浏览器中。我正在尝试加载此库,当我尝试执行所描述的操作时,出现错误

const worker = new Worker('http://localhost:3000/webworker-wasm')
VM114:1 Refused to create a worker from 'http://localhost:3000/webworker-wasm' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'worker-src' was not explicitly set, so 'default-src' is used as a fallback.  

所以我想这与我如何提供该文件有关。我有一个 NestJS 后端,提供该文件的代码看起来像

@Get('webworker-wasm')
private getWebworkerWasm(req: Request, res: Response) {
fs.readFile('./node_modules/stockfish.js/stockfish.wasm.js', (err: any, data: Buffer) => {
res.writeHead(200, {'Content-Type': 'application/wasm'});
res.status(200).end(data);
});
}

此设置中是否有任何不正确的内容或我忘记了什么?

更新:我已经更改了代码,现在错误有点不同

fs.readFile('./node_modules/stockfish.js/stockfish.wasm.js', 'binary', (err: any, data: Buffer) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Request-Method', '*');
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
res.setHeader('Access-Control-Allow-Headers', '*');
res.setHeader('Content-Type', 'application/wasm');
// res.writeHead(200, {'Content-Type': 'application/wasm'});
res.status(200).end(data);
});

给:

x = new Worker('http://localhost:3000/files/webworker-wasm');
VM48:1 Uncaught DOMException: Failed to construct 'Worker': Script at 'http://localhost:3000/files/webworker-wasm' cannot be accessed from origin 'chrome-search://local-ntp'.
at <anonymous>:1:5

如果我可以用铬设置解决这个问题,我的案例很好!

我无法添加评论,所以我将其作为答案发布。

请发布浏览器中显示的所有响应标头。

此外,您正在将JavaScript文件作为WebAssembly提供,application/wasm应该application/javascript

最新更新