Multer图片上传失败,抛出TypeError。将循环结构转换为JSON

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

我正在使用mern stack制作一个简单的应用程序,其中涉及到多个图片上传.我正在使用multer进行多个图片上传。虽然multer成功地上传了图片,但它仍然抛出了一个异常,叫做

TypeError: Converting circular structure to JSON

完整的Exception看起来是这样的。

UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON
[0]     --> starting at object with constructor 'Socket'
[0]     |     property 'parser' -> object with constructor 'HTTPParser'
[0]     --- property 'socket' closes the circle
[0]     at JSON.stringify (<anonymous>)
[0]     at stringify (/home/user/workspace/nodeprojects/tekvertex-mangocoders/node_modules/express/lib/response.js:1123:12)
[0]     at ServerResponse.json (/home/user/workspace/nodeprojects/tekvertex-mangocoders/node_modules/express/lib/response.js:260:14)
[0]     at ServerResponse.send (/home/user/workspace/nodeprojects/tekvertex-mangocoders/node_modules/express/lib/response.js:158:21)
[0]     at /home/user/workspace/nodeprojects/tekvertex-mangocoders/controllers/projects.js:111:13
[0]     at Object.model.saveCategoryStep3 (/home/user/workspace/nodeprojects/tekvertex-mangocoders/models/projects.js:338:5)
[0]     at controller.saveCategoryStep3 (/home/user/workspace/nodeprojects/tekvertex-mangocoders/controllers/projects.js:110:11)
[0]     at Layer.handle [as handle_request] (/home/user/workspace/nodeprojects/tekvertex-mangocoders/node_modules/express/lib/router/layer.js:95:5)
[0]     at next (/home/user/workspace/nodeprojects/tekvertex-mangocoders/node_modules/express/lib/router/route.js:137:13)
[0]     at Immediate.<anonymous> (/home/user/workspace/nodeprojects/tekvertex-mangocoders/node_modules/multer/lib/make-middleware.js:53:37)
[0]     at processImmediate (internal/timers.js:458:21)
[0] (node:31810) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)

我的Express和Multer代码是这样的。

    let multer = require('multer');
const { v4: uuidv4 } = require('uuid');

const DIR = './public/images/check';

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        console.log(req);
        cb(null, DIR);
    },
    filename: (req, file, cb) => {
        const fileName = file.originalname.toLowerCase().split(' ').join('-');
        cb(null, uuidv4() + '-' + fileName)
    }
});

var upload = multer({
    storage: storage,
    fileFilter: (req, file, cb) => {
        if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
            cb(null, true);
        } else {
            cb(null, false);
            return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
        }
    }
});

我的路线是这样的

router.post('/create/step3', [passport.authenticate('jwt', { session: false }), upload.array('imgCollection', 2)], projectsController.mymethod);

这是我在formdata中追加的方式。

let formdata = new FormData();
            for (const file of this.state.fields.avatar) {
                console.log(file);
                formdata.append('imgCollection', file, file.name);
            }

在服务器上,我发现收到的文件是这样的。

文件。[ { fieldname: 'imgCollection' }, { fieldname: 'imgCollection' } ] 。

node.js reactjs express multipartform-data multer
1个回答
0
投票

我得到了它的工作,不知何故,我不知道为什么是现在的工作。

所以我没有像下面那样在路由中使用upload作为中间件。

router.post('/create/step3', [passport.authenticate('jwt', { session: false }), upload.array('imgCollection', 2)], projectsController.mymethod);

我把它用在我的控制器里面 我的路由现在看起来是这样的:

    router.post('/create/step3', passport.authenticate('jwt', { session: false })
, projectsController.mymethod);

所以在我的控制器,即mymethod中的projectsController内

 const getupload = upload.array('imgCollection', 7);
    getupload(req, res, (err) => {
        if (err) {
            return res.send({
                status: process.env.CLIENT_ERROR_CODE,
                message: validation.errors.errors
            });
        }
          //do db stuff
      });
© www.soinside.com 2019 - 2024. All rights reserved.