devnull
devnull

Reputation: 2862

Parsing POST parameters in Nodejs

I am parsing a simple form in a small node script (not using express or any framework) soo I create a function to parse the form body

function postForm(req, res) {

    let body = '';

    req.on('data', data => {
        body += data.toString();
    });

    req.on('end', () => {

        console.log(body);

    });

    res.write('ok');
    res.end();
}

but I do get all fields at once e.g. username=sam&age=22

I understand that in express I could just call body.username or body.age is there a trivial way to do the same ?

rant I can't believe how archaic is to parse a simple form element in nodejs. In go it would be 1 line(r.FormValue("name")) and so in php $_POST["name"]). I must be doing something wrong :)

Upvotes: 0

Views: 68

Answers (2)

Shimon Doodkin
Shimon Doodkin

Reputation: 4569

it depends on what you are sending in the post body. if you send enctype="application/x-www-form-urlencoded"

<form action="/action_page_binary.asp" method="post" enctype="application/x-www-form-urlencoded">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br>
</form>

it will work with:

const querystring = require('querystring');
let post={};
try{
post=querystring.parse(body)
}catch(e){console.log(e.stack)}

,but it cant receive files.

parsing mime multipart encoding it is harder task

<form action="/action_page_binary.asp" method="post" enctype="multipart/form-data">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br>
  <input type="submit" value="Submit">
</form>

boundary is random string. usually lots of "-" then some random string

if you split the text by it(better not split but work with a stream because of large files)

then you have headers then two enters then content. content-encoding depends on headers. In headers you have the filename.

I like this body-parser https://www.npmjs.com/package/multer

see also: https://stackoverflow.com/a/28380690/466363

Upvotes: 1

Jake Holzinger
Jake Holzinger

Reputation: 6063

Node as a module called querystring which you can use to parse the form data. You can also set the encoding of the request so that the chunks are already strings.

const querystring = require('querystring');

function postForm(req, res) {

    req.setEncoding('utf8');

    let body = '';

    req.on('data', data => {
        body += data;
    });

    req.on('end', () => {

        console.log(querystring.parse(body));

    });

    res.write('ok');
    res.end();
}

Upvotes: 1

Related Questions