[英]Render image data in ejs with nodejs
我有一個 nodejs express 系統,想要渲染一個二維碼數據塊的圖像。
我正在從我的 mongoose 模式生成圖像
BaseUserSchema.methods.getProvisionImage = function getProvisionImage() {
qr.toDataURL( JSON.stringify({
account: this.accountName,
code: this.provisionCode,
}),
{},
function (err, url) {
if (err) throw err;
return url;
});
};
並想在頁面上繪制圖像
<img class="img-thumbnail m-2 d-block"
src="<% provisionUser.getProvisionImage() %>"
title="Click to enlarge" >
provisionUser是正確的,我調試時生成代碼最后的值為
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAK ... [etc] ... ==
這一切對我來說都很好——我如何將該字符串轉換成可以顯示的內容?
由於ejs
不支持帶有回調的異步函數,您唯一的解決方法可能是使用 async/await。
你可以試試這個:
BaseUserSchema.methods.getProvisionImage = async function getProvisionImage() {
var data = '';
try {
data = await qr.toDataURL(JSON.stringify({
account: this.accountName,
code: this.provisionCode,
}));
} catch (e) {}
return data;
};
編輯
// this function no longer needs to be async since i moved the async code to another async function
BaseUserSchema.methods.getProvisionImage = function getProvisionImage() {
var data = getData(JSON.stringify({
account: this.accountName,
code: this.provisionCode,
}));
return data;
};
async function getDataURL(str) {
var data = '';
try {
data = await qr.toDataURL(str);
} catch (e) {}
return data;
};
並解釋為什么你的代碼不能工作:
// the getProvisionImage function does not return anything
// since you do not have a return statement in the getProvisionImage scope
BaseUserSchema.methods.getProvisionImage = function getProvisionImage() {
qr.toDataURL( JSON.stringify({
account: this.accountName,
code: this.provisionCode,
}),
{},
function callback(err, url) { // this function is the scope of the return statement bellow
if (err) throw err;
// this will return a value to the caller of this function
// not the caller of getProvisionImage
return url;
});
// this return will work, not the above one in the callback function
return 'data:image/png;bas....';
};
嘗試 promisify 方法,然后將結果等待到將傳遞給ejs
的變量中:
BaseUserSchema.methods.getProvisionImage = function getProvisionImage() {
return new Promise((resolve, reject) => {
qr.toDataURL(JSON.stringify({
account: this.accountName,
code: this.provisionCode,
}), {},
function(err, url) {
if (err) reject(err);
resolve(url);
});
});
};
//...
const img = await provisionUser.getProvisionImage();
//...
src="<% img %>"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.