首页 > 解决方案 > 调用 NextJs Route 并将数据传递给组件

问题描述

我有一个带有 api 路由的 NextJs 应用程序,它调用一个内部页面来生成一个 pdf 文件。

此方法在我的 API 路由中生成 pdf 文件:

function serialize(obj) {
  var str = [];
  for (var p in obj)
    if (obj.hasOwnProperty(p)) {
      str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
    }
  return str.join("&");
};

async function generatePdf(body) {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  // Allows you to intercept a request; must appear before
  // your first page.goto()
  await page.setRequestInterception(true);

  // Request intercept handler... will be triggered with
  // each page.goto() statement
  page.on("request", (interceptedRequest) => {
    // Here, is where you change the request method and
    // add your post data
    var data = {
      method: "POST",
      postData: serialize(body),
      headers: {
        ...interceptedRequest.headers(),
        "Content-Type": "application/x-www-form-urlencoded",
      },
    };

    // Request modified... finish sending!
    interceptedRequest.continue(data);

    // Immediately disable setRequestInterception, or all other requests will hang
    page.setRequestInterception(false);
  });

  const response = await page.goto(process.env.GEN_PDF_URL, {
    waitUntil: "networkidle2",
  });

  const pdf = await page.pdf({
    path: "test.pdf",
    printBackground: true,
    format: "a4",
  });
  const responseBody = await response.text();
  console.log(responseBody);
  await browser.close();

  return pdf;
}

正在从前端调用此方法(sendEmail),并提供数据(req.body)以正确生成pdf页面。我将该数据作为参数传递给该generatePdf方法。

async function sendEmail(req, res) {
  const pdf = await generatePdf(req.body);
  ...

我想知道是否可以使用 nextjs 中 req.body 的提供程序数据生成该页面。这样我就可以动态生成 pdf 文件,因为 Pdf 页面的内容会根据我发送的数据而变化。

标签: javascriptnext.jspuppeteervercel

解决方案


推荐阅读