【问题标题】:Polymer Starter Kit with Node, Express, and Puppeteer包含 Node、Express 和 Puppeteer 的 Polymer Starter Kit
【发布时间】:2018-01-25 16:08:00
【问题描述】:

好的,我是这一切的新手,所以非常感谢任何帮助。

我已经设法使用 Node 和 Express 从我在主目录 (server.js) 中创建的文件的 Polymer 构建目录中提供 Polymer Starter Kit (PSK) 网站:

// Node.js notation for importing packages
var express = require('express');

// Spin up a server
var app = express();

// Serve static files from the main build directory
app.use(express.static(__dirname + '/build/es5-bundled'));

// Render index.html on the main page, specify the root
app.get('/', function(req, res){
  res.sendFile("index.html", {root: '.'});
});

// Tell the app to listen for requests on port 3000
app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

在终端输入“node server.js”,网站在 localhost 3000 上可用,一切正常。

我想要做的是使用节点模块 Puppeteer 在网站访问者单击按钮时从示例网页生成 PDF 文件。这是我放入 PSK 的 my-app.html 文件的 MyApp 类中的代码,单击按钮时会调用该文件。

functionPDFCreate() {

  const puppeteer = require('puppeteer');

  (async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://news.ycombinator.com', { waitUntil: 'networkidle2' });
    await page.pdf({ path: 'hn.pdf', format: 'A4' });

    await browser.close();
  })();

}

但是,上面的函数返回'require is not defined'。我做错了吗?我是否需要以某种方式将 functionPDFCreate 代码放入 server.js 并使用 Express 路由?当 PSK 网站访问者单击按钮时,我究竟如何执行 functionPDFCreate 中的代码?感谢您提供的任何帮助。

【问题讨论】:

  • Require只在nodejs环境下可用,不能在浏览器中使用,除非你使用browserify之类的模块
  • 所以你只能在 server.js 文件中使用 require 而不能在任何聚合物元素中使用?当 PSK 网站访问者单击聚合物元素中的按钮时,我究竟如何在节点环境中执行代码?

标签: javascript node.js express polymer puppeteer


【解决方案1】:

您是否在浏览器上下文中调用functionPDFCreate?正如@YouneL 建议的那样,即使使用 browserify 或 webpack 也无法正常工作。

您应该在为您的 PDF 提供服务的快速应用程序中公开端点:

app.get('/hn', function(req, res) {
    functionPDFCreate().then(() => {
        // now file is written on the disk
        res.sendFile('hn.pdf', { root: '.' });
    });
});

functionPDFCreate 应该是这样的:

const puppeteer = require('puppeteer');

async function functionPDFCreate() {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://news.ycombinator.com', { waitUntil: 'networkidle2' });
    await page.pdf({ path: 'hn.pdf', format: 'A4' });

    await browser.close();
}

在您的浏览器应用中,您应该有这样的下载按钮(与框架无关的示例):

<a href="http://localhost:3000/hn" download="hn.pdf">Download HN PDF</a>

【讨论】:

  • 感谢您花时间回答。在尝试这个建议时,我意识到 /hn 路线由于聚合物入门套件 PRPL 模式而永远无法到达 - 任何想法如何解决这个问题?
  • @HalloweenMan 根据您的示例,我很难说为什么这条路线无法到达。我从未使用过聚合物。在浏览器网址栏中插入http://localhost:3000/hn可以得到pdf吗?
  • 最初,是的,但是一旦访问主页并且聚合物入门套件 PRPL 模式在浏览器中并被缓存,它只是默认为 oops 404 not found。我认为它特定于聚合物入门套件和应用程序 PRPL 模式
  • @HalloweenMan 既然您缩小了问题范围,您应该搜索解决方案或提出仅与聚合物入门套件相关的问题(木偶部分在这里解决)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多