如何解决如何将 req.body 从路由器文件传递到模块?
我正在尝试将我的代码分成模块,以便主文件(应用程序和路由器)保持相对整洁。该网页接受来自表单的 POST 并返回给用户一个使用用户输入生成的 PDF。
在 router.js 中,我想将 if
块的 {} 中的内容分成单独的文件(在第一个块中我将其注释掉)。但是,当我这样做时,单独的文件不会从中间件接收正文信息(我得到 ReferenceError: req is not defined
)。
我如何将 if 块的 {}(这将变得非常冗长,而且还会有更多 if 块,这就是 example1.js 位于文件夹 pdfGenerators 中的原因)到单独的文件中,以便 router.js 保持不变干净吗?
index.html
<!doctype html>
<form method="post" action="sendPDF">
<input name="userInput" type="text">
<button type="submit" name="submit" value="example1">Send Example 1</button>
</form>
<form method="post" action="sendPDF">
<input name="userInput" type="text">
<button type="submit" name="submit" value="example2">Send Example 2</button>
</form>
app.js
const express = require('express');
const app = express();
const path = require("path");
app.use(express.urlencoded({ extended: false }));
//server started?
var port = process.env.PORT || 3000;
app.listen(port,() => {
console.log('Started on PORT 3000');
})
//For local testing only,using Nginx normally
app.use(express.static(path.join(__dirname,"public"),{
extensions: ['html']
}))
//sendPDF routing
require('./router')(app);
router.js
const PDFDocument = require('pdfkit');
module.exports = function(router) {
router.post('/sendPDF',(req,res) => {
if (req.body.submit =='example1') {
require('./pdfGenerators/example1')();
/*const doc = new PDFDocument();
doc.text(req.body.userInput);
// Pipe its output as http response
res.statusCode = 200;
res.setHeader('Content-type','application/pdf');
res.setHeader('Content-disposition','attachment; filename=Example 1.pdf');
doc.pipe(res);
doc.end();*/
}
if (req.body.submit =='example2') {
const doc = new PDFDocument();
doc.text(req.body.userInput);
// Pipe its output as http response
res.statusCode = 200;
res.setHeader('Content-type','attachment; filename=Example 2.pdf');
doc.pipe(res);
doc.end();
}
})
};
example1.js
const PDFDocument = require('pdfkit');
module.exports = function () {
const doc = new PDFDocument();
doc.text(req.body.userInput);
// Pipe its output as http response
res.statusCode = 200;
res.setHeader('Content-type','application/pdf');
res.setHeader('Content-disposition','attachment; filename=Example 1.pdf');
doc.pipe(res);
doc.end();
};
顺便说一句,我的想法是否正确,或者我的架构逻辑是否混乱,这是使用 pdfkit 生成此类 pdf 的有效方法,还是会导致多个同时使用的用户出现问题?
解决方法
您可以使用函数参数作为向 req
模块公开 res
和 example1
对象的一种方式。
在您的路由器中,
const PDFGenerator = require('./pdfGenerators/example1');
module.exports = function(router) {
router.post('/sendPDF',(req,res) => {
if (req.body.submit =='example1') {
PDFGenerator(req,res);
}
// ...
}
然后在您的 PDFGenera 或 example1 模块中,您需要接受这些参数。
module.exports = function (req,res) {
//...
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。