Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express js form data

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

like image 621
Dave Pile Avatar asked Jul 17 '14 10:07

Dave Pile


People also ask

How use FormData in Express JS?

To get started with forms, we will first install the body-parser(for parsing JSON and url-encoded data) and multer(for parsing multipart/form data) middleware. var express = require('express'); var bodyParser = require('body-parser'); var multer = require('multer'); var upload = multer(); var app = express(); app.

What is FormData () in JS?

The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the fetch() or XMLHttpRequest. send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data" .


1 Answers

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
like image 86
Mritunjay Avatar answered Oct 03 '22 08:10

Mritunjay