0

I'm using nodejs and express 4.16 for my project. So for the body parsing I'm not using the deprecated body-parser but something like this

app.use(express.json()); //Used to parse JSON bodies
app.use(express.urlencoded()); //Parse URL-encoded bodies

as the doc says.

So, in one of my controller I'm have some problem with only one post control. This is my code:

var express = require('express');

const router = express.Router();
const passport = require('passport');

//multer
const multer = require('multer')
var diskStorage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, '/tmp/')
    },
    filename: function (req, file, cb) {
      cb(null, file.fieldname + '-' + Date.now())
    }
  })
//var memoryStorage = multer.memoryStorage()
const upload = multer({ storage: diskStorage })

router.post('/update-cloud', passport.authenticate('jwt', {session: false}), upload.single('file'), async (req, res) => {
    try {

        console.log(req);

        return res.status(200);
    } catch (err) {
        console.log(err);
        res.status(500).json({
            "error": 500,
            "descr": err
        });
    }
})

router.post('/cloud-items/:id', async (req, res) => {
    try {

        console.log(req.body);

        return res.status(200);
    } catch (err) {
        console.log(err);
        res.status(500).json({
            "error": 500,
            "descr": err
        });
    }
})

module.exports = router;

in the second controller my req.body seems empty, in the first not. I tried to console.log() this, and this is a buffer, not persed, like this:

 body: <Buffer 2d 2d 2d 2d 2d 2d 57 65 62 4b 69 74 46 6f 72 6d 42 6f 75 6e 64 61 72 79 46 6b 6a 69 6e 53 33 67 4b 66 66 36 32 42 41 55 0d 0a 43 6f 6e 74 65 6e 74 2d ... >,

If I try to add to the second controller the middleware passport and muter, all works fine. Why this? I've got crazy before discovered this.

1 Answer 1

1

The data being passed is multipart form data not json or urlencoded. You need to add middle ware to handle it, such as multer, https://www.npmjs.com/package/multer

Sign up to request clarification or add additional context in comments.

1 Comment

I resolve changing this: -router.post('/cloud-items/:id', async (req, res) => { to this: router.post('/cloud-items/:sosid', passport.authenticate('jwt', {session: false}), upload.none(), async (req, res) => {...} But I don't understand why this is necessary. In all my code the post param works without this middleware. By the way thanks for the help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.