Express js form data - javascript

Can someone please tell me the recommended (up to date) way to get POSTed form data in express.
So many tutorials/ posts etc talk about bodyParser but this is no longer bundled with Express and other blogs etc recommend using urlencoded directly, but now this is not available either.
Trying to find accurate information on these frameworks or technologies is doing my head in.
BTW what I am intrerested in is very simple and small 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

You can make use of express-formidable module to that.
install 'express-formidable' by the following command
npm install express-formidable
the simple example is as follows
const express = require('express');
const formidable = require('express-formidable');
var app = express();
app.use(formidable());
app.post('/upload', (req, res) => {
//req.fields contains non-file fields
//req.files contains files
res.send(JSON.stringify(req.fields));
});
Click here for further description

From the README of body-parser:
This does not handle multipart bodies, due to their complex and
typically large nature.
The above is going to work with x-www-form-urlencoded and json but it will NOT work with any multipart. form-data is also multipart with the header multipart/form-data.
In case of form-data, your best solution would be to use express-formidable.

As stated in this StackOverflow answer:
Express 4.16+ has implemented their own version of body-parser so you do not need to add the dependency to your project. You can run it natively in express
app.use(express.json()); // Used to parse JSON bodies
app.use(express.urlencoded()); // Parse URL-encoded bodies using query-string library
// or
app.use(express.urlencoded({ extended: true })); // Parse URL-encoded bodies using qs library
See also: query-string vs qs

I noticed #HubballiHuli answer was to use a package called express-formidable.
You don't need to use this unnecessary package, it provide one (small) file of code.
Instead you can do it yourself (now removing the dependency).
Here is the formidableMiddleware file:
'use strict';
const formidable = require('formidable');
function parse(opts, events) {
return (req, res, next) => {
if (req.express_formidable && req.express_formidable.parsed) {
next();
return;
}
const form = new formidable.IncomingForm();
Object.assign(form, opts);
let manageOnError = false;
if (events) {
events.forEach((e) => {
manageOnError = manageOnError || e.event === 'error';
form.on(e.event, (...parameters) => { e.action(req, res, next, ...parameters); });
});
}
if (!manageOnError) {
form.on('error', (err) => {
next(err);
});
}
form.parse(req, (err, fields, files) => {
if (err) {
next(err);
return;
}
Object.assign(req, { fields, files, express_formidable: { parsed: true } });
next();
});
};
}
module.exports = parse;
exports.parse = parse;
Now on how to use it:
const express = require('express');
const formidableMiddleware = require('./formidableMiddleware.js');
var app = express();
app.use(formidableMiddleware());
app.post('/upload', (req, res) => {
//req.fields contains non-file fields
//req.files contains files
res.send(JSON.stringify(req.fields));
});
I wrote an article on unnecessary packages a while ago and why not to use them:
https://medium.com/#alexjamesdunlop/unnecessary-packages-b3623219d86

Besides the solutions with formidable, there is another module which I have been using in my recent projects since 2019. The module express-form-data can be easily declared in your server file like:
const express = require('express');
const formData = require('express-form-data');
app.use(formData.parse());
app.post('/image-upload', (req, res) => {
console.log(req.files);
})
...
In case of image uploading, for instance, req.files will provide all relevant data you need for handling the files such as path, size, filename, etc.

If you would like to apply the formidableMiddleware to only one API route and not globally, this is how you would pass the value.
This would be useful if u want to mix between different headers to pass to the API for other API's which you which u do not want the formidableMiddleware API to be applied.
const express = require('express');
const formidable = require('express-formidable');
var app = express();
app.post('/mypath', formidableMiddleware(), (req, res) => {
// rest of the code
})

Related

ReactJS Axios and Node.js - Data undefined? [duplicate]

I have the following Node.js code:
var express = require('express');
var app = express.createServer(express.logger());
app.use(express.bodyParser());
app.post('/', function(request, response) {
response.write(request.body.user);
response.end();
});
Now if I POST something like:
curl -d user=Someone -H Accept:application/json --url http://localhost:5000
I get Someone as expected. Now, what if I want to get the full request body? I tried doing response.write(request.body) but Node.js throws an exception saying "first argument must be a string or Buffer" then goes to an "infinite loop" with an exception that says "Can't set headers after they are sent."; this also true even if I did var reqBody = request.body; and then writing response.write(reqBody).
What's the issue here?
Also, can I just get the raw request without using express.bodyParser()?
Starting from express v4.16 there is no need to require any additional modules, just use the built-in JSON middleware:
app.use(express.json())
Like this:
const express = require('express')
app.use(express.json()) // <==== parse request body as JSON
app.listen(8080)
app.post('/test', (req, res) => {
res.json({requestBody: req.body}) // <==== req.body will be a parsed JSON object
})
Note - body-parser, on which this depends, is already included with express.
Also don't forget to send the header Content-Type: application/json
Express 4.0 and above:
$ npm install --save body-parser
And then in your node app:
const bodyParser = require('body-parser');
app.use(bodyParser);
Express 3.0 and below:
Try passing this in your cURL call:
--header "Content-Type: application/json"
and making sure your data is in JSON format:
{"user":"someone"}
Also, you can use console.dir in your node.js code to see the data inside the object as in the following example:
var express = require('express');
var app = express.createServer();
app.use(express.bodyParser());
app.post('/', function(req, res){
console.dir(req.body);
res.send("test");
});
app.listen(3000);
This other question might also help: How to receive JSON in express node.js POST request?
If you don't want to use the bodyParser check out this other question: https://stackoverflow.com/a/9920700/446681
As of Express 4, the following code appears to do the trick.
Note that you'll need to install body-parser using npm.
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.listen(8888);
app.post('/update', function(req, res) {
console.log(req.body); // the posted data
});
For 2019, you don't need to install body-parser.
You can use:
var express = require('express');
var app = express();
app.use(express.json())
app.use(express.urlencoded({extended: true}))
app.listen(8888);
app.post('/update', function(req, res) {
console.log(req.body); // the posted data
});
You should not use body-parser it is deprecated. Try this instead
const express = require('express')
const app = express()
app.use(express.json()) //Notice express.json middleware
The app.use() function is used to mount the specified middleware function(s) at the path which is being specified. It is mostly used to set up middleware for your application.
Now to access the body just do the following
app.post('/', (req, res) => {
console.log(req.body)
})
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json())
var port = 9000;
app.post('/post/data', function(req, res) {
console.log('receiving data...');
console.log('body is ',req.body);
res.send(req.body);
});
// start the server
app.listen(port);
console.log('Server started! At http://localhost:' + port);
This will help you. I assume you are sending body in json.
This can be achieved without body-parser dependency as well, listen to request:data and request:end and return the response on end of request, refer below code sample. ref:https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/#request-body
var express = require('express');
var app = express.createServer(express.logger());
app.post('/', function(request, response) {
// push the data to body
var body = [];
request.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
// on end of data, perform necessary action
body = Buffer.concat(body).toString();
response.write(request.body.user);
response.end();
});
});
In my case, I was missing to set the header:
"Content-Type: application/json"
Try this:
response.write(JSON.stringify(request.body));
That will take the object which bodyParser has created for you and turn it back into a string and write it to the response. If you want the exact request body (with the same whitespace, etc), you will need data and end listeners attached to the request before and build up the string chunk by chunk as you can see in the json parsing source code from connect.
The accepted answer only works for a body that is compatible with the JSON format. In general, the body can be accessed using
app.use(
Express.raw({
inflate: true,
limit: '50mb',
type: () => true, // this matches all content types
})
);
like posted here. The req.body has a Buffer type and can be converted into the desired format.
For example into a string via:
let body = req.body.toString()
Or into JSON via:
let body = req.body.toJSON();
If you're lazy enough to read chunks of post data.
you could simply paste below lines
to read json.
Below is for TypeScript similar can be done for JS as well.
app.ts
import bodyParser from "body-parser";
// support application/json type post data
this.app.use(bodyParser.json());
// support application/x-www-form-urlencoded post data
this.app.use(bodyParser.urlencoded({ extended: false }));
In one of your any controller which receives POST call use as shown below
userController.ts
public async POSTUser(_req: Request, _res: Response) {
try {
const onRecord = <UserModel>_req.body;
/* Your business logic */
_res.status(201).send("User Created");
}
else{
_res.status(500).send("Server error");
}
};
_req.body should be parsing you json data into your TS Model.
I'm absolutely new to JS and ES, but what seems to work for me is just this:
JSON.stringify(req.body)
Let me know if there's anything wrong with it!
Install Body Parser by below command
$ npm install --save body-parser
Configure Body Parser
const bodyParser = require('body-parser');
app.use(bodyParser);
app.use(bodyParser.json()); //Make sure u have added this line
app.use(bodyParser.urlencoded({ extended: false }));
What you claim to have "tried doing" is exactly what you wrote in the code that works "as expected" when you invoke it with curl.
The error you're getting doesn't appear to be related to any of the code you've shown us.
If you want to get the raw request, set handlers on request for the data and end events (and, of course, remove any invocations of express.bodyParser()). Note that the data events will occur in chunks, and that unless you set an encoding for the data event those chunks will be buffers, not strings.
You use the following code to log post data:
router.post("/users",function(req,res){
res.send(JSON.stringify(req.body, null, 4));
});

How to manage request data on entry file in node js

In Node Js, on the entry file e.g. index.js, How can I get requested data either as Form-data or Form-URL-encoded or Raw JSON data in middleware?
In my project, I am handling various API request,
Few requests contain file type so requesting as form-data.
Few requests do not contain file type so requests are coming as Form-URL-encoded.
Now the main problem is before routing, I need a specific field from req.body in the middleware.
But I am getting req.body as undefined.
For reference here is my index.js file:
const express = require('express');
const app = express();
app.use(express.raw());
app.use(express.urlencoded({ extended: false }));
app.use((req, res, next) => {
const routes_handler = require('./routes/index.js')(app, express, req);
next();
})
app.listen(3000, () => {
console.log("Server running at Port " + 3000);
});
and the routes/index.js file as follows:
module.exports = function (app, express, req) {
console.log(req.body);
//I need here data of req.body for all requests type (form data, URL-encoded, raw JSON)
app.post('/', function (req, res) {
console.log("Here I can get the requested body easily", req.body)
res.send('Hello World');
});
app.post('*', function (req, res) {
res.send({
code: 0,
message: 'No Content',
status_code: 204,
data: {
error: 'API not found!'
}
});
});
}
Also, I know for file type data, POSTMAN will send the request as Form-data, not as Form-url-encoded. So which I should choose Formidable or Multer?
The way you get all the data in index.js is by creating middlewares for your application, every time any routes that go into your application will be passed through this middleware.
Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.
The below middleware will simply listen to all routes & adds up request time to request time, here goes the code
let express = require('express')
let app = express()
let bodyParser = require("body-parser")
app.use(bodyParser.json())
let requestTime = function (req, res, next) { // simply updating add the requestBody using the middleware
req.requestTime = Date.now();
req.json_body = req.body;
next()
}
app.use(requestTime) // requestTime is the middleware here
app.get('/', function (req, res) {
var responseText = 'Hello World!<br>'
responseText += '<small>Requested at: ' + req.requestTime + '</small>'
res.send(responseText)
})
app.listen(3000)
Few things to note here
Always add interceptor above all routes
Don't forget to add next() inside the middleware, else it will not go to the next route.
Now, coming to the second part of your question which is accessing body,formdata, etc
You can use body-parser npm module to achieve that, something like this
Starting from Express 4, body-parser comes inbuilt with it, so you can try out something
app.use(express.json());
app.use(
bodyParser.urlencoded({
extended: false
})
);
Now, the last bit, you don't need Multer for formdata, but for file upload like multipart/form-data you will need this. Both are good in their own ways, I would go for Multer.
Hope this will help you :)
I believe the body-parser module is your answer.
https://www.npmjs.com/package/body-parser
Add the following line before the routes in your index.js after installing the body-parser package.
app.use(bodyParser.json())

Questions on to use Node.js as local server with Braintree?

I'm not new to JavaScript but I am new to Node.js and back end languages. I have a very simple question.
I've installed and setup Node.js on my computer and I'm attempting to get a server going between my static files & directory(s) and my browser to be able to send and receive requests. I've downloaded Braintree's free Sandbox (found here) for practice to get some faux transactions going just to gain a better understanding of how this can work.
I set up a local server by running npm install -g http-server on my command line and then http-server to set it up.
I then received the following message in my command line:
Starting up http-server, serving ./public
Available on:
http://127.0.0.1:8080
http://10.0.1.4:8080
Hit CTRL-C to stop the server
So, with this setup...if I wanted to do get() and post() methods and see it rendered and communicating between my "server" and my static files. How do I do this? For example, if I were to set up Braintree's sandboxed environment and then create a clientToken using the following code from Braintree's website
const http = require('http'),
url = require('url'),
fs = require('fs'),
express = require('express'),
braintree = require('braintree');
const gateway = braintree.connect({
environment: braintree.Environment.Sandbox,
merchantId: "xxxxx",
publicKey: "xxxxx",
privateKey: "xxxxx" //blocked out real numbers for privacy
});
Here is the remaining code I hae to create a "client Token" for a transaction...and here is the guide I'm following via Braintree's website...
http.createServer((req,res) => {
gateway.clientToken.generate({
},(err, response) => {
if(err){
throw new Error(err);
}
if(response.success){
var clientToken = response.clientToken
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(clientToken);
res.end("<p>This is the end</p>");
} else {
res.writeHead(500, {'Content-Type': 'text/html'});
res.end('Whoops! Something went wrong.');
}
});
}).listen(8080,'127.0.0.1');
So, my question is...if I wanted to generate send a token to a client using the get() method...how would I do that? Would it have to be a separate js file? How would they be linked? If they're in the same directory will they just see each other?
Here is an example on Braintree's website of how a client token may be sent:
app.get("/client_token", function (req, res) {
gateway.clientToken.generate({}, function (err, response) {
res.send(response.clientToken);
});
});
How could this be integrated into my current code and actually work? I apologize if these are elementary questions, but I would like to gain a better understanding of this. Thanks a lot in advance!
I don't know much about braintree, but usually you would use somthing like express.js to handel stuff like this. So I'll give you some quick examples from an app I have.
#!/usr/bin/env node
var http = require('http');
var app = require('../server.js');
var models = require("../models");
models.sync(function () {
var server = http.createServer(app);
server.listen(4242, function(){
console.log(4242);
});
});
So that's the file that gets everything started. Don't worry about models, its just syncing the db.
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
// share public folder
app.use(express.static(path.join(__dirname, 'public')));
require('./router.js')(app);
module.exports = app;
next up is the server.js that ties eveything together. app.use() lines are for adding middleware and the app.use(logger('dev')); sets the route logger for what your looking for.
app.use(express.static(path.join(__dirname, 'public'))); shares out all files in the public directory and is what your looking for for static files
var path = require('path');
module.exports = function(app){
//catch
app.get('*', function(req, res){
res.sendFile(path.join(__dirname, '..', 'public', 'index.html'));
});
}
last piece is the router.js. This is were you would put all of you get and post routes. generally I've found that if you see app.get or app.post in examples there talking about express stuff. It's used a lot with node and just makes routing way easier.
Also if your using tokens a route would look like this.
app.get('/print', checkToken, function(req, res){
print.getPrinters(function(err, result){
response(err, result, req, res);
});
});
function checkToken(req, res, next){
models.Tokens.findOne({value: req.headers.token}, function(err, result){
if(err){
res.status(500).send(err);
}else if(result == null){
console.log(req.headers);
res.status(401).send('unauthorized');
}else{
next();
}
});
}
so any route you want to make sure had a token you would just pass that function into it. again models is for db

How can I get the body of the postrequest in nodejs?

I am getting my head around node.js and trying to construct a post request, this is my server.js file:
module.exports = function(app) {
app.post('/api/postrequest', function(req, res) {
console.log('inside postrequest');
console.log(req.body); //this is empty????
});
// application -------------------------------------------------------------
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
};
I would like to filter data from the request so try to verify what is in req.body. The problem is it is empty : {}. To test I am using Postman to submit the request:
http://localhost:8080/api/postrequest
Using the raw format to post this json:
{"name":"Eddie"}
You will need to use a middleware like body-parser to do that. Do an npm install body-parser and require it in your app with
var bodyParser = require('body-parser');
Then use it like so
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({'extended': 'true'}));

How to access POST form fields in Express

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?
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.
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.
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.
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.
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();
})
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
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
});
app.use(express.bodyParser());
Then for app.post request you can get post values via req.body.{post request variable}.
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);
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).
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.
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
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!
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;
}
express.urlencoded
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.
Request streaming worked for me
req.on('end', function() {
var paramstring = postdata.split("&");
});
var postdata = "";
req.on('data', function(postdataChunk){
postdata += postdataChunk;
});
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));
})
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)
})
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");
})
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');
}
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');
});
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'
Other answers talk about the middleware to use on the server side. My answer attempt to provide developers with a simple playbook to debug the problem themselves.
In this question, the situation is:
You have a form on the client side
The data is sent by clicking on Submit button and you don't use JavaScript to send requests (so no fetch, axios, xhr,... but we can extend the solution for these cases later)
You use Express for the server side
You cannot access data in your Express code. req.body is undefined
There are some actions that you can do to find the solution by yourself:
Open the Network tab and search for your request.
Check the request header Content-Type. In this situation (form submit), the header is likely application/x-www-form-urlencoded or multipart/form-data if you send a file (with enctype="multipart/form-data" in the form tag)
Now check your Express code if you use the appropriate middleware to parse incoming requests.
If your Content-Type is application/x-www-form-urlencoded then you should have app.use(express.urlencoded({extended: true})) in your code.
If your Content-Type is multipart/form-data: because Express doesn't have a built-in middleware to parse this kind of request, you should another library for that. multer is a good one.
If you have done all the steps above, now you can access data in req.body :). If you have problems with the syntax, you should check the Express document page. The syntax could be changed because this question is posted a long time ago.
Now, we can extend this simple playbook for other cases that involve JavaScript code. The key is to check the request Content-Type. If you see application/json then you should use app.use(express.json()) in your code.
In summary, find your request Content-Type, then use the appropriate middleware to parse it.
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

Categories