【问题标题】:Express generate and return QR code on GET request根据 GET 请求快速生成并返回 QR 码
【发布时间】:2020-01-22 16:15:02
【问题描述】:

我正在尝试根据快速请求生成 QR 码。它从 URL 参数中获取值,并使用文件流作为原始图像返回 QR 码。

const express = require('express');
const router = express.Router();
const QRCode = require('qrcode');

router.get('/qr/:content', function(req, res, next){
let content = req.params.content

// Filestream goes here

})

这就是我尝试的方式,但是我从未使用过文件流,我无法让它工作:

let code = QRCode.toFileStream(new stream.Writable, conent)
code.pipe(res);

这是我正在使用的库:https://www.npmjs.com/package/qrcode

【问题讨论】:

  • 你确定这不是错字吗:let code = QRCode.toFileStream(new stream.Writable, ===> conent <==)

标签: node.js express filestream


【解决方案1】:

试试这个代码:

import QRCode from 'qrcode';
import { PassThrough } from 'stream';


router.get('/qr/:content', async (req, res, next) => {
    try{
        const content = req.params.content;            
        const qrStream = new PassThrough();
        const result = await QRCode.toFileStream(qrStream, content,
                    {
                        type: 'png',
                        width: 200,
                        errorCorrectionLevel: 'H'
                    }
                );

        qrStream.pipe(res);
    } catch(err){
        console.error('Failed to return content', err);
    }
}

【讨论】:

  • 完美!这就是我一直在寻找的。​​span>
  • 你应该得到赏金。我只需要等待 24 小时才能授予它。
猜你喜欢
  • 1970-01-01
  • 2018-04-05
  • 1970-01-01
  • 2020-07-01
  • 2021-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多