alfianrehanusa
alfianrehanusa

Reputation: 2124

node.js, express, how to get data from body form-data in post request

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?

Upvotes: 26

Views: 58563

Answers (6)

alfianrehanusa
alfianrehanusa

Reputation: 2124

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.

Upvotes: 64

yatendra srivastava
yatendra srivastava

Reputation: 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.

    

Upvotes: -1

Safaetul Ahasan Piyas
Safaetul Ahasan Piyas

Reputation: 1783

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.

Upvotes: 1

Pedro Arantes
Pedro Arantes

Reputation: 5379

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

Upvotes: 1

piticent123
piticent123

Reputation: 323

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.

Upvotes: 4

Ghoul Ahmed
Ghoul Ahmed

Reputation: 4836

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.

Upvotes: 5

Related Questions