19 comments

@Logan 2019-10-04 16:33:52

Written at Express version 4.16

Inside the router function you can use req.body property to access the post variable. For example if this was the POST route of your form, it would send back what you input:

function(req,res){
      res.send(req.body);

      //req.body.email would correspond with the HTML <input name="email"/>
}

P.S. for those who are familiar with PHP: In order to access PHP's $_GET variable we use req.query and to access PHP's $_POST variable we use req.body in Node.js.

@Chirag 2017-11-06 13:46:43

Use express-fileupload package:

var app = require('express')();
var http = require('http').Server(app);
const fileUpload = require('express-fileupload')

app.use(fileUpload());

app.post('/', function(req, res) {
  var email = req.body.email;
  res.send('<h1>Email :</h1> '+email);
});

http.listen(3000, function(){
  console.log('Running Port:3000');
});

@ARUNBALAN NV 2016-09-21 13:08:46

I could find all parameters by using following code for both POST and GET requests.

var express = require('express');
var app = express();
const util = require('util');
app.post('/', function (req, res) {
    console.log("Got a POST request for the homepage");
    res.send(util.inspect(req.query,false,null));
})

@lfender6445 2017-01-16 20:52:38

do you mind updating the answer with your version of express?

@sagar saini 2018-03-07 05:25:46

You are using req.query.post with wrong method req.query.post works with method=get, method=post works with body-parser.

Just try this by changing post to get :

<form id="loginformA" action="userlogin" method="get">
<div>
    <label for="email">Email: </label>
    <input type="text" id="email" name="email"></input>
</div>
<input type="submit" value="Submit"></input>  
</form>

And in express code use 'app.get'

@HamidKhan 2017-10-11 15:30:23

Post Parameters can be retrieved as follows:

app.post('/api/v1/test',Testfunction);
http.createServer(app).listen(port, function(){
    console.log("Express server listening on port " + port)
});

function Testfunction(request,response,next) {
   console.log(request.param("val1"));
   response.send('HI');
}

@vdegenne 2018-04-14 09:09:43

do you realize this won't work ? param is used for GET requests.. not POST and your example lacks of details, very confusing for new comers. And on top of that request.param is actually deprecated, so your example is wrong on so many levels.

@lakesare 2016-08-05 18:05:57

Backend:

import express from 'express';
import bodyParser from 'body-parser';

const app = express();
app.use(bodyParser.json()); // add a middleware (so that express can parse request.body's json)

app.post('/api/courses', (request, response) => {
  response.json(request.body);
});

Frontend:

fetch("/api/courses", {
  method: 'POST',
  body: JSON.stringify({ hi: 'hello' }), // convert Js object to a string
  headers: new Headers({ "Content-Type": "application/json" }) // add headers
});

@seme 2018-01-19 20:51:45

var express        =         require("express");
var bodyParser     =         require("body-parser");
var app            =         express();

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

app.get('/',function(req,res){
  res.sendfile("index.html");
});
app.post('/login',function(req,res){
  var user_name=req.body.user;
  var password=req.body.password;
  console.log("User name = "+user_name+", password is "+password);
  res.end("yes");
});
app.listen(3000,function(){
  console.log("Started on PORT 3000");
})

@Drew Noakes 2012-08-17 15:30:04

Things have changed once again starting Express 4.16.0, you can now use express.json() and express.urlencoded() just like in Express 3.0.

This was different starting Express 4.0 to 4.15:

$ npm install --save body-parser

and then:

var bodyParser = require('body-parser')
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
})); 

The rest is like in Express 3.0:

Firstly you need to add some middleware to parse the post data of the body.

Add one or both of the following lines of code:

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

Then, in your handler, use the req.body object:

// assuming POST: name=foo&color=red            <-- URL encoding
//
// or       POST: {"name":"foo","color":"red"}  <-- JSON encoding

app.post('/test-page', function(req, res) {
    var name = req.body.name,
        color = req.body.color;
    // ...
});

Note that the use of express.bodyParser() is not recommended.

app.use(express.bodyParser());

...is equivalent to:

app.use(express.json());
app.use(express.urlencoded());
app.use(express.multipart());

Security concerns exist with express.multipart(), and so it is better to explicitly add support for the specific encoding type(s) you require. If you do need multipart encoding (to support uploading files for example) then you should read this.

@SooDesuNe 2012-09-16 23:21:43

If this answer isn't working right, make sure you have the content-type header set, for example: curl -d '{"good_food":["pizza"]}' -H 'content-type:application/json' "http://www.example.com/your_endpoint"

@chovy 2012-09-23 06:32:41

what is the difference between posting a form with name/value pairs and posting a JSON body? Do they both show up in req.body?

@Kristján 2013-01-10 06:46:48

@chovy Yes, they do. bodyParser abstracts JSON, URL-encoded and multipart data into the req.body object.

@linuxdan 2014-02-12 00:39:20

express seems to be discouraging bodyParser => expressjs.com/api.html#bodyParser

@Drew Noakes 2014-02-12 13:38:56

@linuxdan, thanks. I've brought the answer up to date.

@Christiaan Westerbeek 2014-02-25 11:38:54

Next to using content-type:application/json you should be POSTing JSON like so: {"a": 1}. The following results in the variable a not being available in req.body -> {a: 1}

@Drew Noakes 2014-02-25 12:03:45

@Chris, that's right. JSON requires properties to be in " quotes, even if JavaScript does not.

@Konstantin Isaev 2014-04-14 14:10:22

express.json() etc. are part of connect, not express, so, middlewars are should be referenced by connect.middelwarename instead of express.middleware

@araneae 2014-06-13 14:00:59

This code gave me errors as middleware is no longer bundled with Express; you'll have to use body-parser: github.com/senchalabs/connect#middleware

@Fabien Sa 2014-08-12 16:28:07

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

@Adnan 2014-11-08 14:39:20

hats off to you! I just wasted a whole day figuring what was wrong.

@Martin Carel 2014-11-15 21:58:07

For reading json using Express 4, only the app.use(require('body-parser').json()) line is sufficient. And then you can read the json data from your request's body object, i.e. req.body, from within a route definition.

@Erik Reppen 2014-11-21 03:28:25

I'm trying to understand why JSON.parse('{'+params.split('=') .join(':') .split('&') .join(',')+'}'); needed to be its own separate middleware component rather than something Express.js just does out of the box. How is sifting through now dozens of dependencies to make the simplest things happen any easier than just using http.listen?

@user1980175 2014-12-23 11:58:34

You're already telling express what to use. Omit the following and it'll work just fine. app.use(express.json()); // to support JSON-encoded bodies app.use(express.urlencoded()); // to support URL-encoded bodies

@Hairi 2018-01-22 15:40:02

Can I have both URL-encoded and json-type data? If yes, what if we have same keys in both objects?

@cwingrav 2016-11-18 14:20:48

I was searching for this exact problem. I was following all the advice above but req.body was still returning an empty object {}. In my case, it was something just as simple as the html being incorrect.

In your form's html, make sure you use the 'name' attribute in your input tags, not just 'id'. Otherwise, nothing is parsed.

<input id='foo' type='text' value='1'/>             // req = {}
<input id='foo' type='text' name='foo' value='1' /> // req = {foo:1}

My idiot mistake is your benefit.

@Saif Al Falah 2017-01-24 05:33:50

Same problem here. But I was using the name attribute from the start. Let's see what the problem is.

@yeelan 2014-06-12 04:13:49

Update for Express 4.4.1

Middleware of the following is removed from Express.

  • bodyParser
  • json
  • urlencoded
  • multipart

When you use the middleware directly like you did in express 3.0. You will get the following error:

Error: Most middleware (like urlencoded) is no longer bundled with Express and 
must be installed separately.


In order to utilize those middleware, now you need to do npm for each middleware separately.

Since bodyParser is marked as deprecated, so I recommend the following way using json, urlencode and multipart parser like formidable, connect-multiparty. (Multipart middleware is deprecated as well).

Also remember, just defining urlencode + json, the form data will not be parsed and req.body will be undefined. You need to define a middleware handle the multipart request.

var urlencode = require('urlencode');
var json = require('json-middleware');
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();

app.use(json);
app.use(urlencode);
app.use('/url/that/accepts/form-data', multipartMiddleware);

@Mohammad Faizan khan 2014-10-29 06:17:40

i guess this is really bad feature updation

@Mohammad Faizan khan 2014-10-29 06:26:16

just for the sake of body parse i have to do lots of code. what the hack is

@DustinB 2014-11-26 03:30:22

I had to add ".middleware()" to require('json-middleware') to get this to work.

@Lalit Umbarkar 2015-08-30 10:37:32

For Express 4.1 and above

As most of the answers are using to Express, bodyParser, connect; where multipart is deprecated. There is a secure way to send post multipart objects easily.

Multer can be used as replacement for connect.multipart().

To install the package

$ npm install multer

Load it in your app:

var multer = require('multer');

And then, add it in the middleware stack along with the other form parsing middleware.

app.use(express.json());
app.use(express.urlencoded());
app.use(multer({ dest: './uploads/' }));

connect.json() handles application/json

connect.urlencoded() handles application/x-www-form-urlencoded

multer() handles multipart/form-data

@med116 2014-07-22 02:19:43

This will do it if you want to build the posted query without middleware:

app.post("/register/",function(req,res){
    var bodyStr = '';
    req.on("data",function(chunk){
        bodyStr += chunk.toString();
    });
    req.on("end",function(){
        res.send(bodyStr);
    });

});

That will send this to the browser

email=emailval&password1=pass1val&password2=pass2val

It's probably better to use middleware though so you don't have to write this over and over in each route.

@Daniel 2016-05-04 16:55:23

sooo.... handy, for those that don't want to rely on a library that will sooner or later be deprecated

@maioman 2016-10-27 10:44:09

you could easily build your own middleware

@Nawaraj 2019-08-31 12:18:32

This is a great answer but why there is extra text "----------------------------359856253150893337905494 Content-Disposition: form-data; name="fullName" Ram ----------------------------359856253150893337905494--" I don't want that number.

@zeah 2015-04-29 18:01:27

Request streaming worked for me

req.on('end', function() {
    var paramstring = postdata.split("&");
});

var postdata = "";
req.on('data', function(postdataChunk){
    postdata += postdataChunk;
});

@John Slegers 2016-01-07 01:09:49

Better than doing postdata.split("&") would be to load core module querystring = require('querystring') and then parse your postdata with querystring.parse(postdata);

@mplewis 2014-05-10 20:52:49

Note for Express 4 users:

If you try and put app.use(express.bodyParser()); into your app, you'll get the following error when you try to start your Express server:

Error: Most middleware (like bodyParser) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.

You'll have to install the package body-parser separately from npm, then use something like the following (example taken from the GitHub page):

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

var app = express();

app.use(bodyParser());

app.use(function (req, res, next) {
  console.log(req.body) // populated!
  next();
})

@Tommy 2014-05-27 11:27:13

Thanks very much for this information. Was pulling my hair out trying to deal with the new way of using bodyParser! This was a big breakthrough - really appreciate

@Mohammad Faizan khan 2014-10-29 06:12:31

heplp: body-parser deprecated bodyParser: use individual json/urlencoded middlewares

@yonran 2011-04-19 02:21:23

Note: this answer is for Express 2. See here for Express 3.

If you're using connect/express, you should use the bodyParser middleware: It's described in the Expressjs guide.

// example using express.js:
var express = require('express')
  , app = express.createServer();
app.use(express.bodyParser());
app.post('/', function(req, res){
  var email = req.param('email', null);  // second parameter is default
});

Here's the original connect-only version:

// example using just connect
var connect = require('connect');
var url = require('url');
var qs = require('qs');
var server = connect(
  connect.bodyParser(),
  connect.router(function(app) {
    app.post('/userlogin', function(req, res) {
      // the bodyParser puts the parsed request in req.body.
      var parsedUrl = qs.parse(url.parse(req.url).query);
      var email = parsedUrl.email || req.body.email;;
    });
  })
);

Both the querystring and body are parsed using Rails-style parameter handling (qs) rather than the low-level querystring library. In order to parse repeated parameters with qs, the parameter needs to have brackets: name[]=val1&name[]=val2. It also supports nested maps. In addition to parsing HTML form submissions, the bodyParser can parse JSON requests automatically.

Edit: I read up on express.js and modified my answer to be more natural to users of Express.

@murvinlai 2011-04-19 05:19:03

Hmm ok. i try the bodyParser(). the doc says i can get it from req.query() but i got nothing. that's very weird. I have no problem with Get tho.

@yonran 2011-04-19 06:23:14

No, req.query is ONLY the GET params. You get the POST data through req.body. The function req.params() includes them both.

@HostileFork says dont trust SE 2012-04-11 20:58:52

A stray click downvoted this answer accidentally without me noticing! Now StackOverflow won't let me change it. Esp. frustrating as this was helpful...I upvoted another of your good answers that I wasn't explicitly looking for to make up for it. :)

@HenioJR 2014-02-18 13:52:34

You shoudn't use app.use(express.bodyParser()). BodyParser is a union of json + urlencoded + mulitpart. You shoudn't use this because multipart will be removed in connect 3.0.

To resolve that, you can do this:

app.use(express.json());
app.use(express.urlencoded());

It´s very important know that app.use(app.router) should be used after the json and urlencoded, otherwise it does not work!

@Sean Lynch 2013-11-21 22:00:47

Security concern using express.bodyParser()

While all the other answers currently recommend using the express.bodyParser() middleware, this is actually a wrapper around the express.json(), express.urlencoded(), and express.multipart() middlewares (http://expressjs.com/api.html#bodyParser). The parsing of form request bodies is done by the express.urlencoded() middleware and is all that you need to expose your form data on req.body object.

Due to a security concern with how express.multipart()/connect.multipart() creates temporary files for all uploaded files (and are not garbage collected), it is now recommended not to use the express.bodyParser() wrapper but instead use only the middlewares you need.

Note: connect.bodyParser() will soon be updated to only include urlencoded and json when Connect 3.0 is released (which Express extends).


So in short, instead of ...

app.use(express.bodyParser());

...you should use

app.use(express.urlencoded());
app.use(express.json());      // if needed

and if/when you need to handle multipart forms (file uploads), use a third party library or middleware such as multiparty, busboy, dicer, etc.

@FelipeAls 2013-11-24 20:14:13

Added a comment below question so more people see your concerns and advice. Would other solutions detailed in Andrew Kelley blog post (still) relevant in your opinion? (just asking for others, my needs are purely for internal tools ^^)

@Sean Lynch 2013-11-26 01:58:07

@FelipeAls - Yes, and I meant to reference Andrew's post as well. Any of those suggestions (taking into consideration the downfalls of each) are relevant.

@Sean Lynch 2013-11-26 01:59:34

Also, once Connect 3.0 is released without including multipart() as part of bodyParser(), bodyParser() becomes "safe" again, but you will need to explicitly enable multipart support using a third party library.

@Chinthaka Senanayaka 2012-04-09 19:18:39

app.use(express.bodyParser());

Then for app.post request you can get post values via req.body.{post request variable}.

@Eogcloud 2014-01-22 15:29:32

your post request variable here, is that the id of the input field in question or the whole form or what?

@Mohammad Faizan khan 2014-10-29 06:11:21

express.bodyParser() is deprecated. update your answer

@David 2012-01-20 11:12:56

Given some form:

<form action='/somepath' method='post'>
   <input type='text' name='name'></input>
</form>

Using express

app.post('/somepath', function(req, res) {

    console.log(JSON.stringify(req.body));

    console.log('req.body.name', req.body['name']);
});

Output:

{"name":"x","description":"x"}
req.param.name x

@cawecoy 2013-06-22 23:19:59

didnt work for me. need to use app.use(express.bodyParser());

@Mohammad Faizan khan 2014-10-29 06:10:23

@cawecoy absolutely right same here but express.bodyParser() not working as well for me it deprecated

@cawecoy 2014-10-31 21:43:59

@MohammadFaizankhan it was an experimental work, I didn't use express anymore, can't help now. Google it for similar functions to express.bodyParser(). good lucky!

Related Questions

Sponsored Content

9 Answered Questions

[SOLVED] Proxy with express.js

27 Answered Questions

[SOLVED] How to auto-reload files in Node.js?

  • 2009-12-29 00:08:49
  • disc0dancer
  • 267792 View
  • 421 Score
  • 27 Answer
  • Tags:   javascript node.js

29 Answered Questions

31 Answered Questions

[SOLVED] Node / Express: EADDRINUSE, Address already in use - Kill server

  • 2010-11-02 06:08:27
  • Skawful
  • 489036 View
  • 387 Score
  • 31 Answer
  • Tags:   node.js

20 Answered Questions

[SOLVED] jQuery get specific option tag text

6 Answered Questions

[SOLVED] HTML button to NOT submit form

  • 2010-05-13 10:01:12
  • arik
  • 170723 View
  • 352 Score
  • 6 Answer
  • Tags:   javascript html

17 Answered Questions

[SOLVED] How to decide when to use Node.js?

3 Answered Questions

[SOLVED] Node.js / Express.js - How does app.router work?

9 Answered Questions

10 Answered Questions

[SOLVED] AngularJS : Initialize service with asynchronous data

Sponsored Content