How to Access Post Form Fields in Express

How to access POST form fields in Express

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.

How to get data from post form with express.js server

I searched all day for the solution and then I found out that I didn't gave id to the form.

This is the not fixed:

    <form action="/admin/loginInput" method="POST">
<input name="username" id="username" class="username" placeholder="Username">
<input name="password" id="password" class="password" placeholder="Password">
<button name="password" type="submit" class="submit">Login</input>
</form>

This is the fixed:

<form id="loginform" action="/admin/loginInput" method="POST">
<input name="username" id="username" class="username" placeholder="Username">
<input name="password" id="password" class="password" placeholder="Password">
<button name="password" type="submit" class="submit">Login</input>
</form>

When I gave id to the form I could acces it from the express server with req.body.

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 js form data

You should install body-parser through npm-install. Now it comes as a separate middleware.

After that add following line in your app.js

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
// in latest body-parser use like below.
app.use(bodyParser.urlencoded({ extended: true }));

It parses the post request as an object. You will get your variables in req.body.

In your post request handler.

app.post('/post',function(request,response){
console.log(request.body) //you will get your data in this as object.
})

Edit 1

The answer above was for the question specifically asked, the OP was looking for the bodyParser(deprecated) which was not part of express anymore.

Since the title of the question is very generic and the answer doesn't include all aspects of form-data, I will put @StLia's answer as an edit.

Body-Parser Readme

This does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules:

  • busboy and
    connect-busboy
  • multiparty and
    connect-multiparty
  • formidable
  • multer

In NodeJS express; How can I get form properties from a form post?

How can I get the form attributes such as name and method and action? Do I need to do something to the in built body parser?

No, only form elements designed to contain data in the form are sent automatically with the form post. Attributes of the parent form element such as name and action are not sent.

A trick that is often used in forms it to insert a hidden element in the form (one that the user does not see) and put data into that element that you want sent to the server. Then the server can access the data like any other named form element. You can either populate those elements when the form is originally designed or you can populate them dynamically with Javascript at any time before the form is submitted.

For example:

 <form method='post' name='form1' action="/form1Submit">
<input type="hidden" name="action" value="post">
<input type="hidden" name="formName" value="form1">
Enter your data here: <input name="data">
<input type='submit'>
</form>

Assuming your have the body-parser middleware appropriately configured, then when this form is submitted you will be able to access req.body.action and req.body.formName and req.body.data in your express server.

cannot access the POST form data sent by HTML/Javascript code at node js code

The problem is FormData is sending body encoded as multipart/form-data. You'll have to add middleware able to handle multipart body format. Busboy or multer for example.

Example of using multer to upload a file and send userID field:

// --- form
<form action="/submitForTest" enctype="multipart/form-data" method="post">
<input type="file" name="uploaded_file">
<input type="text" name="userID">
<input type="submit" value="Submit">
</form>
// --- server
var multer = require('multer')
var upload = multer({ dest: './uploads/' }) // where the uploaded files will be stored
app.post('/submitForTest', upload.single('uploaded_file'), function (req, res) {
// req.file is the name of your file in the form above, here 'uploaded_file'
// req.body will hold the text fields, if there were any
console.log(req.file, req.body)
});

Or to send your data in urlencoded or json format. Something like that for json for example:

function submitForTest()
{
var userID = document.getElementById('userid').value;
fetch('http://MY-SERVER:3000/submitForTest', {
method: "POST",
headers: {
'Content-type': 'application/json',
},
body: JSON.stringify({ userID }),
});
}

How to make express app not change page on POST request

It's not an express thing, just apart of how forms operate in HTML.

You can look at this answer which is similar:
Prevent redirect after form is submitted

Just make your post request via js instead of a submit action of your form.

How to get body form data in nodejs express?

You can use multer npm package to parse multipart form data for you. This is a simple middleware, so it should be easy to use. more on multer.

The urlencoded middleware (which you used) handles x-www-form-urlencoded content type.



Related Topics



Leave a reply



Submit