javascript - 调用 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 页面的内容会根据我发送的数据而变化。
解决方案
推荐阅读
- reactjs - 为什么表单数据不在 req.body 中?
- php - 为什么在没有任何条款的情况下尝试访问 taxonomy.php 页面时出现 404 错误,(Wordpress 看不到分类页面)
- regex - 使用正则表达式匹配子字符串
- youtube-data-api - 超出配额 - 从我的应用上传 YouTube 链接 - 在仪表板上看不到超出配额
- windows - 从长路径启动 win32 应用程序
- javascript - 在 mongoose 文档中检索对象的所有键
- r - 有没有办法根据一组字符串是否显示为较长字符串的一部分来过滤它们?
- reactjs - 如何使用 react-native-testing-library getByRole
- bash - 是否可以使用在循环中更改其名称的变量作为 shell 脚本中函数的输入?
- reactjs - 如何通过反应原生导航传递参数