Jeanluca Scaljeri
Jeanluca Scaljeri

Reputation: 29159

Error when loading WebAssembly file from NestJs backend

I'm trying to load a WebAssembly file into the browser. I'm trying to load this library and when I try to do what is described I get an error

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.  

So I guess it has to do with how I serve that file. I have a NestJS backend, and the code serving that file looks like

@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);
    });
}

Is there anything in this setup that is incorrect or did I forget something?

UPDATE: I've changed the code a bit and now the error is a bit different

   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);
    });

gives:

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

My my case its fine if I can fix this with a chrome setting!

Upvotes: 0

Views: 384

Answers (1)

The Wayward Developer
The Wayward Developer

Reputation: 491

I can’t add a comment, so I post this as an answer.

Please post all the response headers as seen in the browser.

Also, you’re serving a JavaScript file as WebAssembly, application/wasm should be application/javascript.

Upvotes: 2

Related Questions