问题描述
我正在编写使用 firebase 和 firebase 函数的应用程序。任务是编写将生成页面 pdf 的函数(需要对页面进行身份验证)。为此,我使用 puppeteer。但是发回前面的pdf保存为空白页。
1
我还有 firebase 功能,可以从前端接收令牌,制作新的 CustomToken,在 puppeteer 中打开无头浏览器,并在此浏览器的 cookie 中发送这个 CustomToken
// the function that handles the saving of pdf on client
function download(data,filename,type) {
const file = new Blob([data],{ type });
if (window.navigator.msSaveOrOpenBlob) {
// IE10+
window.navigator.msSaveOrOpenBlob(file,filename);
} else {
// Others
const a = document.createElement('a');
const url = URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(() => {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
},0);
}
}
//the function that is called on 'download pdf button'
const onDownloadbrochure = async (brochureId) => {
try {
const token = await firebase.auth().currentUser.getIdToken();
const baseUrl = window.location.origin;
const response = await axios({
method: 'get',url: `${process.env.REACT_APP_API_BASE_URL}/pdfGeneratorurl=${baseUrl}/brochures/${brochureId}/preview`,headers: {
Authorization: token,Accept: 'application/pdf',crossdomain: true,mode: 'no-cors',},});
download(response.data,'pdf','application/pdf');
return response;
} catch (error) {
return error;
}
};
在那条路线的前面,我们从 cookie 中提取令牌,登录应用程序并发送请求以获取页面所需的所有数据,在页面完全加载后,puppeteer 应该制作 pdf 并将其发送回客户端。
app.get('/',async (request,response) => {
try {
const url = request.query.url;
const token = request.get('Authorization') || '';
const decoded = jwt_decode(token);
const uid = decoded.user_id;
if (!url) {
return response.send(`Invalid url: ${url}`);
}
const customToken = await admin.auth().createCustomToken(uid);
if (!customToken) {
return response.send(`Invalid token: ${customToken}`);
}
const browser = await puppeteer.launch({
args: ['--no-sandBox'],});
const page = await browser.newPage();
await page.setJavaScriptEnabled(true);
await page.goto(url,{
waitUntil: ['networkidle2','domcontentloaded'],});
await page.setCookie({ name: 'token',value: customToken });
await page.goto(url,'domcontentloaded','load'],});
await page.evaluate(() => console.log(`url is ${location.href}`));
await page.emulateMediaType('screen');
const pdf = await page.waitForTimeout(5000).then(() =>
page.pdf({
format: 'a4',printBackground: true,margin: {
top: '20px',bottom: '20px',right: '20px',left: '20px',}),);
await page.deleteCookie({ name: 'token' });
await browser.close();
return response.type('application/pdf').send(pdf);
} catch (error) {
return response.status(404).send(error.message);
}
});
module.exports = functions
.runWith({
timeoutSeconds: 120,memory: '2GB',})
.https.onRequest(app);
但最终在客户端保存响应数据后,我只收到空的 pdf。我完全不明白什么是错的,为什么会这样。请帮忙!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)