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

时间:2019-10-11 21:45:30

标签: nestjs webassembly

我正在尝试将WebAssembly文件加载到浏览器中。我正在尝试加载this库,并且当我尝试执行所描述的操作时会收到错误

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

我的情况下,如果我可以使用镀铬设置修复它,那就很好了!

1 个答案:

答案 0 :(得分:1)

我无法添加评论,因此将其发布为答案。

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

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