如何将qrcode返回到dataurl编码以进行json响应

时间:2018-09-04 03:24:14

标签: javascript node.js express

我编写了一个nodejs函数来对qrcode进行编码,并希望将结果返回给调用者函数,以创建json响应。但是我不知道为什么它不能返回数据响应。我的代码有什么问题。你能帮我吗?

Navigate
我要创建的

json响应

OnActivated

1 个答案:

答案 0 :(得分:0)

QRCode.toDataURL使用回调函数(一旦异步检索到url,它将使用参数调用回调函数,因此您不能直接返回它。)

但是,如果不指定回调,它将返回Promise。您可以返回Promise,并在Promise上使用then方法来获取值。

gen_qrcode : function() {
    var QRCode = require('qrcode');
    var qr_url = "https://www.google.com";
    return QRCode.toDataURL(qr_url, { errorCorrectionLevel: 'M' });
}

//other function
object_name.gen_qrcode().then((url) => {
    let json_object = JSON.stringify({
       status: 1,
       description: 'Success',
       qr_data: url 
    })
    console.log(json_object); //do something with json_object
})

或者,您可以将Async / Await(browser support)与指令here.一起使用