节点:从中间件向函数发送数据

Node: send data from middlware to function

我正在使用 express,我需要创建一些用于验证的中间件

我有点像

代码:

app.use(‘/upload', fromData)
app.use(‘/upload', function firstUpload(req, res, next) {
    return fileHandler(req, res, next)
        .then((status) => {
            res.statusCode = 201;
            res.end(status)
        }).catch((err) => {
            return next(new appError(500, err));
        });
});

现在我使用另一个来自Handler的函数

function formData(req) {

 return new Promise((resolve, reject) => {
 const form = new formidable.IncomingForm();
  form.maxFileSize = 100 * 1024 * 1024;
  form.keepExtensions = true;
  form.multiEntry = true;
  form.parse(req, (err, fields, files) => {
    const filesInfo = Object.keys(files).map((key) => {
        const file = files[key];
        const filePath = file.path;
        const fileExt = path.extname(file.name);
        const fileName = path.basename(file.name, fileExt);
        return {filePath, fileExt};
    });
 }
  Resolve(filesInfo)
}

我需要的是 return 来自 formData 函数的数据 Resolve(filesInfo) fileHandler 函数,我该怎么做? fileHandler 函数需要获取 filesInfo

这里不需要承诺。中间件使用 next 函数作为 callback 转到下一个处理程序。在此之前,您应该将中间件中的数据放入 req 对象中。之后,您可以通过从 req. filesInfo.

获取来使用
function formData(req, res, next) {
  const form = new formidable.IncomingForm();
  form.maxFileSize = 100 * 1024 * 1024;
  form.keepExtensions = true;
  form.multiEntry = true;
  form.parse(req, (err, fields, files) => {
    if (err || fields.length === 0) {
       res.status(500).json({ message: 'you are done' }); // <- this is where you stop the request with an error.
    }
    const filesInfo = Object.keys(files).map((key) => {
        const file = files[key];
        const filePath = file.path;
        const fileExt = path.extname(file.name);
        const fileName = path.basename(file.name, fileExt);
        return {filePath, fileExt};
    });
    req.filesInfo = filesInfo;
    next();
  }
}

function fileHandler(req, res) {
  console.log(req.filesInfo); /* <- you can also get the filesInfo here */ 
  return Promise.resolve({});
}

app.use(‘/upload', fromData)
app.use(‘/upload', function(req, res, next) {
    // console.log(req.filesInfo); => You can get your filesInfo here and do whatever you want
    return fileHandler(req, res, next)
        .then((status) => {
            res.statusCode = 201;
            res.end(status)
        }).catch((err) => {
            return next(new appError(500, err));
        });
});