Search code examples
reactjsnode.jsnestjsqr-code

Why doesn't my QR Code show up when streamed from the server


I am generating a QR Code in my NestJS backend and passing to the browser. The backend in my service contains the following code, which is then called by the controller and passed back to the browser:

async pipeQrCodeStream(stream: any, otpauthUrl: string) {
    const filePath = '/qrcode.png'
    
    await qrcode.toFile(filePath, otpauthUrl);
    return qrcode.toFileStream(stream, otpauthUrl);
  }

As you can see from the example above, I have also saved the code to a file to check it looks ok and the PNG it saves looks fine.

On the browser side I have a React component containing the following code.

const MyQrPage = () => {
    const [qrCodeUrl, setQrCodeUrl] = useState(null);

    useEffect(() => {
        const fetchQrCode = async () => {
            const response = await axios.post(
                '/myqrcode',
                {responseType: 'blob'}
            );
            const qrCodeBlob = await response.data;
            const qrCodeUrl = URL.createObjectURL(new Blob([qrCodeBlob]));
            setQrCodeUrl(qrCodeUrl);
        };

        fetchQrCode();
        
    }, []);

  return (
    <Container maxWidth="sm">
      {qrCodeUrl && (
        <div>
            <img src={qrCodeUrl} alt="QR Code" />
        </div>
        )}
    </Container>
  );
};

When the page loads, all I see is an image placeholder illustrating that the image cannot be found. When inspecting in Chrome I see the HTML attribute is the following:

<img src="blob:http://localhost:3000/da8280e8-3fa1-40f7-a0d6-864b4297a765" alt="QR Code">

Note that port 3000 is my React app being serviced. If I copy that URL and put it into my browser I do see a load of data, which starts with PNG so I think the data is there.

So grateful for any assistance you can provide.


Solution

  • You are passing responseType to data parameter of axios, whereas configuration is the third param.

    Modify your axios request to

    const response = await axios.post(
        '/myqrcode', 
        null, 
        {responseType: "blob"}
    );