23

I have a simple node.js app. I want to get post body from user.

app.js

var express = require('express');
var app = express();

app.use(express.json());

app.post('/api/user', function (req, res) {
    console.log(req.body);
    console.log(req.body.username);
});

module.exports = app;

server.js

var app = require('./app.js');

var server = app.listen(3000, function () {

    var port = server.address().port;

    console.log('Web App Hosted at http://localhost:%s',port);

});

When i launch it with node server.js, its fine. When i check it with postman, enter image description here

in console, it returns

Web App Hosted at http://localhost:3000
{}
undefined

I have the newest express.

And i have try other thing like add body-parser, add header to content-type, add express.urlencoded(), but none work. i need to get data from form-data like postman on picture above. How i can get it?

alfianrehanusa
  • 1,424
  • 2
  • 15
  • 30
  • Possible duplicate of [What does body-parser do with express?](https://stackoverflow.com/questions/38306569/what-does-body-parser-do-with-express) – zero298 Jun 25 '19 at 16:21
  • @zero298 i think is not, because i use the newest express. So i no need body-parser – alfianrehanusa Jun 26 '19 at 02:15

6 Answers6

57

after hours, i found it.

body-parser its not required because in newest express is included.

i have found how to get form-data, it require multer(for parsing multipart/form data) middleware. i have found it in here.

first install multer

npm install multer --save

import multer in your app. for example in my code

var express = require('express');
var app = express();
var multer = require('multer');
var upload = multer();

// for parsing application/json
app.use(express.json()); 

// for parsing application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true })); 

// for parsing multipart/form-data
app.use(upload.array()); 
app.use(express.static('public'));

app.post('/api/user', function (req, res) {
    console.log(req.body);
    console.log(req.body.username);
});

module.exports = app;

so, it can receive form-data, raw, or x-www-form-urlencoded.

alfianrehanusa
  • 1,424
  • 2
  • 15
  • 30
  • 7
    I have also had the same issue and spend 3 hours trying to figure out what went wrong. Finally, I also forgot to include my multer function in my routes :) – Alisher Musurmonv Dec 20 '19 at 05:17
4

you need install body-parser to parse req.body

var bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

body-parser extract the entire body portion of an incoming request stream and exposes it on req.body.

Ghoul Ahmed
  • 4,446
  • 1
  • 14
  • 23
3

Express specifies in their API docs that you have to use one of the provided middlewares to give the body a value. They made this decision because there are many different kinds of formats HTTP request bodies can take, and they don't want to assume which one your app uses.

piticent123
  • 193
  • 1
  • 7
1

Did you add Content-Type: application/json to Headers? I had the same problem and was solved adding Content-Type: application/json.

Pedro Arantes
  • 5,113
  • 5
  • 25
  • 60
1

I had face same problem.I had solved following way:

  1. First install 'express-fileupload' package.

  2. include express-fileupload

    fileUpload = require('express-fileupload')

  3. enable files upload

    app.use(fileUpload({ createParentPath: true }));

N.B: Or You can use multer package instead of express-fileupload package.as your wish.

Safaetul Ahasan Piyas
  • 1,285
  • 1
  • 8
  • 10
-1
const express = require("express");
var multer = require('multer');
var upload = multer();
const app = express();
var multiparty = require('multiparty');
var util = require('util');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(upload.array()); 
app.use(express.static('public'));
// default options
const addFileDetail =  (req, res,next) => {
//app.post('/upload', function(req, res) {
    
  var sampleFile = req.body.filepath;
   console.log(req.body.filepath);
//   var uploads = "./"+req.body.filepath+"/"+req.body.org+"/"+req.body.type+'/';
//       await createDir(uploads);
//   let uploadPath = uploads;

//   if (!req.files || Object.keys(req.files).length === 0) {
//     return res.status(400).send('No files were uploaded.');
//   }

//   // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
//   sampleFile = req.files.sampleFile;
//   uploadPath = __dirname + uploadPath + sampleFile.name;

//   // Use the mv() method to place the file somewhere on your server
//   sampleFile.mv(uploadPath, function(err) {
//     if (err)
//       return res.status(500).send(err);
var form = new multiparty.Form();

form.parse(req, function(err, fields, files) {
  res.writeHead(200, { 'content-type': 'text/plain' });
  res.write('received upload:\n\n');
  res.end(util.inspect({fields: fields, files: files}));
             console.log('fields: %@', fields);
             console.log('files: %@', files);
});
    // res.send('File uploaded!');
//   });
}

const createDir = (dirPath) => {
    fs.mkdir(dirPath, { recursive: true }, (err) => {
        if (err) {
            throw err;
        }
        console.log("Directory is created.");
    });
}

module.exports = {
   // getfile: getfile,
    addFileDetail: addFileDetail,
   // viewFiles: viewFiles
};
 i am getting issue in this.