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

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.


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.


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.