req.body 在 multer 中间件之后不存在

问题描述 投票:0回答:0

我的代码执行以下操作:

  1. 解析多部分表单数据
  2. 上传Book details到mongodb atlas,获取id传给下一个中间件
  3. 上传该书的 pdf,文件名作为步骤 2 中生成的书 ID
  4. 使用 req.body 做进一步处理

下面是我的

routes.js

const express=require("express")
const {processor,uploadBookDetails}= require('../controller/controller')
const {upload} = require('../utils/utils')
const router = express.Router()
const multer = require('multer')
const parser = multer()

router.post("/upload",parser.any(),uploadBookDetails, upload.single("file"), processor)

module.exports=router

下面是我的控制器

uploadBookDetails
processor

const processor = (req, res) => {
    console.log(req.body)     // this outputs {}
    res.status(200)
        .send("Processing successful");
};

const uploadBookDetails = (req, res, next) => {
    console.log(req.body)
    //const book =  uploading code
    console.log("Book Uploaded")
    req.id=book._id
    next()
}

下面是我的

upload
中间件:

const mongouri = process.env.MONGO_URI
const {
    GridFsStorage
} = require("multer-gridfs-storage");
const multer = require("multer");
const storage = new GridFsStorage({
    url: mongouri,
    file: (req, file) => {
        return new Promise((resolve, reject) => {
            const filename = req.id;
            const fileInfo = {
                filename: filename,
                bucketName: "newBucket"
            };
            resolve(fileInfo);
        });
    }
});

const upload = multer({
    storage
});

module.exports={
    upload
}

我的问题是当

processor
中间件运行时
req.body
输出
{}
.

注意:我已经使用

parser.any()
作为中间件,以便像
uploadBookDetails
中间件一样解析多形式数据,因为在解析之前它是
{}
在使用
parser.any()
之后我的 req.body 变成了 {},在 req.body 正确输出之前
.

它试图找到解决方案,但我找不到任何解决方案。提前致谢。

node.js express mongoose multer multer-gridfs-storage
© www.soinside.com 2019 - 2024. All rights reserved.