[javascript] How to access POST form fields

Here is my simple form:

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

Here is my Express.js/Node.js code:

app.post('/userlogin', function(sReq, sRes){    
    var email = sReq.query.email.;   
}

I tried sReq.query.email or sReq.query['email'] or sReq.params['email'], etc. None of them work. They all return undefined.

When I change to a Get call, it works, so .. any idea?

This question is related to javascript node.js post express

The answer is


from official doc version 4

const express = require('express')
const app = express()
app.use(express.json());
app.use(express.urlencoded({ extended: true })) 

app.post('/push/send', (request, response) => {
  console.log(request.body)
})

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

Request streaming worked for me

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

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

Express v4.17.0

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

app.post('/userlogin', (req, res) => {    

   console.log(req.body) // object

   var email = req.body.email;

}

Demo Form

Another Answer Related


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.


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');
});

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.


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.


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
});

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


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();
})

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.


Update

As of Express version 4.16+, their own body-parser implementation is now included in the default Express package so there is no need for you to download another dependency.

You may have added a line to your code that looks like the following:

app.use(bodyparser.json()); //utilizes the body-parser package

If you are using Express 4.16+ you can now replace that line with:

app.use(express.json()); //Used to parse JSON bodies

This should not introduce any breaking changes into your applications since the code in express.json() is based on bodyparser.json().

If you also have the following code in your environment:

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

You can replace that with:

app.use(express.urlencoded()); //Parse URL-encoded bodies

A final note of caution: There are still some very specific cases where body-parser might still be necessary but for the most part Express’ implementation of body-parser is all you will need for the majority of use cases.

(See the docs at expressjs/bodyparser for more details).


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'


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");
})

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));
})

when you are using POST method in HTML forms, you need to catch the data from req.body in the server side i.e. Node.js. and also add

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

OR

use method='GET' in HTML and and catch the data by req.query in the server side i.e. Node.js


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);

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.


app.use(express.bodyParser());

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


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!


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');
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to post

How to post query parameters with Axios? How can I add raw data body to an axios request? HTTP POST with Json on Body - Flutter/Dart How do I POST XML data to a webservice with Postman? How to set header and options in axios? Redirecting to a page after submitting form in HTML How to post raw body data with curl? How do I make a https post in Node Js without any third party module? How to convert an object to JSON correctly in Angular 2 with TypeScript Postman: How to make multiple requests at the same time

Examples related to express

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block jwt check if token expired Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] npm notice created a lockfile as package-lock.json. You should commit this file Make Axios send cookies in its requests automatically What does body-parser do with express? SyntaxError: Unexpected token function - Async Await Nodejs Route.get() requires callback functions but got a "object Undefined" How to redirect to another page in node.js