soldair / node-qrcode

qr code generator
MIT License
7.55k stars 631 forks source link

"You need to specify a canvas element" error when using Cloudflare Workers with `qrcode` #349

Open bkyerv opened 1 year ago

bkyerv commented 1 year ago

I am encountering an error when attempting to generate a QR code using the qrcode library within a Cloudflare Worker. The error message is "You need to specify a canvas element".

Error stack:

Error: You need to specify a canvas element
    at getCanvasElement (index.js:2058:15)
    at Object.render (index.js:2069:20)
    at renderToDataURL (index.js:2088:32)
    at renderCanvas (index.js:2214:18)
    at qr (index.js:2307:31)
    at new Promise (<anonymous>)
    at Object.fetch (index.js:2306:24)
    at async jsonError (index.js:2337:12) {
  stack: Error: You need to specify a canvas element
    at…306:24)
    at async jsonError (index.js:2337:12),
  message: You need to specify a canvas element
}

Environment:

Using Cloudflare Workers.
Implementing the server API of the qrcode library.

Steps to Reproduce:

Set up a Cloudflare Worker.
Integrate the qrcode library to generate a QR code.
Execute the worker function to generate the QR code.

Expected Result: The QR code should be generated successfully.

Actual Result: Encountering the above error, which seems to suggest a canvas element is required.

I would appreciate any guidance or suggestions on how to resolve this issue, especially considering the context of using Cloudflare Workers where a DOM-based canvas isn't available.

Thank you!

Below is the source code for the worker

export default {
    async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {

        if (request.method !== 'POST') {
            return new Response('Method not allowed', { status: 405 });
        }

        try {
            const payload = await request.json();

            const qr = await QRCode.toDataURL(payload.uniqueTitle, { type: 'image/webp' });

                        return new Response(qr);

        } catch (e) {
            console.error(e);
            return new Response(null, { status: 500});
        }
    },
};
lexakozakov commented 1 year ago

same here

kamil-homernik commented 1 year ago

I'm also looking for a solution to generate QR codes without access to DOM

feri-irawan commented 10 months ago

Try using node-canvas

evanoxu commented 8 months ago

same here

techieshark commented 7 months ago

Not a fix for this library, but if anyone is desperate here might be some leads

abusedmedia commented 1 month ago

A solution is just using QRCode.toString instead of QRCode.toDataURL. You'll get an SVG instead of a PNG. Good enough for many cases.