Akash Verma
Akash Verma

Reputation: 77

Getting req.body empty using form-data in postman

when i post request using postman by form data like this, i got empty object in my express js :

enter image description here

var storage = multer.diskStorage({
    destination: function (request, file, callback) {
        callback(null, 'public/images/course');
    },
    filename: function (request, file, callback) {
        console.log(req.file)
        if (request.files) {
            console.log(file)
           // TODO: consider adding file type extension
           fileExtension = file.originalname.split('.')[1]
           return callback(null, `${request.path}-${request.files[0]._id.toString()}.${fileExtension}`);
        }
        // fallback to the original name if you don't have a book attached to the request yet. 
        return callback(null, file.originalname) 
    }
});

var uploadImg = multer({storage : storage}).single('thumbnail')

router.post('/course',  async(req, res) => {
    console.log(req.body) // console logs empty object {}
    try{
    const course = new Course({
                name : req.body.name,
                thumbnail : 'placeholder'
            })  
            uploadImg(req, res, function (err) {
                if (err) {
                  console.log(err.message);
                  // An error occurred when uploading
                  return
                }
                console.log('Everything went fine');
                // Everything went fine
              })
    }catch(e){
        res.status().send()
    }  
})

and i cant use multer before to parse data because first i wanna generate an id by mongoose then i use multer like above.

for example i can't do it like :

router.post('/course', upload.single(), async(req, res) => {
    console.log(req.body) // console logs empty object {}
    try{
    const course = new Course({
                name : req.body.name,
                thumbnail : 'placeholder'
            })  
            uploadImg(req, res, function (err) {
                if (err) {
                  console.log(err.message);
                  // An error occurred when uploading
                  return
                }
                console.log('Everything went fine');
                // Everything went fine
              })
    }catch(e){
        res.status().send()
    }  
})

it gives an ERROR : unexpected field.

so is there any way to get my req.body data first so i can generate my mongoose id and then upload the image

//index.js

const express = require('express')
var multer = require('multer');
require('./db/mongoose')
const userRouter = require('./routers/user')
const taskRouter = require('./routers/task')
const courseRouter = require('./routers/course')

var bodyParser = require('body-parser');

const app = express()
const port = process.env.PORT || 3000



// // for parsing application/json
 app.use(bodyParser.json()) 

 app.use(bodyParser.urlencoded({ extended: true })); 

app.use(express.json())
 app.use(express.static('public'))

app.use(userRouter)
app.use(taskRouter)
app.use(courseRouter)


app.listen(port, () => {
    console.log('connected succefully')
})

Upvotes: 3

Views: 7890

Answers (3)

Irtza Mazhar
Irtza Mazhar

Reputation: 131

In the latest version of express for sending requests using form-data, you need to add multer on your server-side. Like that:

npm install --save multer

Then in your main server file add these lines.

const multer  = require('multer');
const upload = multer();
app.use(upload.array());

Upvotes: 4

Ahmad Sharif
Ahmad Sharif

Reputation: 4435

Use express-busboy to parse postman form-data.

var app = express();
var expressBusboy = require('express-busboy');
expressBusboy.extend(app);

Upvotes: 2

Danizavtz
Danizavtz

Reputation: 3280

If you are using express version >= 4.16 You can for sure remove the body-parser lib. You can also remove from package.json One of the new features from express `4.16 was bundle express with body-parser. If it's the case, remove the lines with body-parser lib, and use only body parser that comes bundled with express:

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

If it's version <=4.16 also install body-parser in you package.json

const bodyparser = require('body-parser')
...
app.use(bodyparser.json())
app.use(bodyparser.urlencoded({extended: true}))

You should stick with one but not mix them.

Upvotes: 1

Related Questions