Nodejs - How to show qr-image result in view

拈花ヽ惹草 提交于 2020-01-01 10:28:13

问题


I use qr-image plugin for Nodejs to generate a QR code and it works pretty good.

The problem is showing result image in ejs.

var express = require('express');
var router = express.Router();
var qr = require('qr-image');

router.get('/', function(req, res) {
    var code = qr.image("text to show in qr", { type: 'png', ec_level: 'H', size: 10, margin: 0 });
    res.type('png');
    code.pipe(res);
    // res.render('index', { title: 'QR Page', qr: code });
});

When i uncomment last line, nodejs crashs. How to send code to view as a variable?

Update:

This code returns [object Object] in result page.

var code = qr.image("text to show in qr", { type: 'png', ec_level: 'H', size: 10, margin: 0 });
res.render('index', { title: 'QR Page', qr: code });

Also console.log(code) shows this:

{ _readableState:
   { highWaterMark: 16384,
     buffer: [],
     length: 0,
     pipes: null,
     pipesCount: 0,
     flowing: false,
     ended: false,
     endEmitted: false,
     reading: false,
     calledRead: false,
     sync: true,
     needReadable: false,
     emittedReadable: false,
     readableListening: false,
     objectMode: false,
     defaultEncoding: 'utf8',
     ranOut: false,
     awaitDrain: 0,
     readingMore: false,
     decoder: null,
     encoding: null },
  readable: true,
  domain: null,
  _events: {},
  _maxListeners: 10,
  _read: [Function] }

回答1:


You're trying to stuff a rendered image into a template engine; it's not going to work.

You should instead have an image tag in the template that points to a URL that responds with the image.

// Edit based on comment

router.get('/qr/:text', function(req,res){
   var code = qr.image(req.params.text, { type: 'png', ec_level: 'H', size: 10, margin: 0 });
   res.setHeader('Content-type', 'image/png');
   code.pipe(res);
}

Then in your html template, make an image tag with the src set to /qr/whatever text and you should be in good shape.



来源:https://stackoverflow.com/questions/27490742/nodejs-how-to-show-qr-image-result-in-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!