7

I am learning Node.js. I am trying to learn it without using 3rd party modules or frameworks.

I am trying to figure out how I can get the POST data from each individual input.

I am making a login system:

<form method="POST" action="/login">
   <input name="email" placeholder="Email Address" />
   <input name="password" placeholder="Password" />
</form>

So the user logins and the input data is POSTed to the server.

The Node.js server is ready for this POST :

 var http = require('http');
 var server = http.createServer(function(req, res) {


 if(req.method == POST && req.url == '/login') {


 var body = "";

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


 req.on('end', function () {
 console.log(body);
 });

 }

 });
 server.listen(80);

The node.js server code above can console.log the body. For example, this will console.log the post data like this:
[email protected] password=thisismypw

BUT how do I get the input data individually? I think in PHP I could target each input this way:

  $_POST['email']  and $_POST['password']

and I could put these values into a variable and use them to INSERT or CHECK the database.

Can someone please show me how I can do this in Node.js? Please no modules barebones please!

0

1 Answer 1

10

For application/x-www-form-urlencoded forms (the default) you can typically just use the querystring parser on the data:

var http = require('http'),
    qs = require('querystring');

var server = http.createServer(function(req, res) {
  if (req.method === 'POST' && req.url === '/login') {
    var body = '';
    req.on('data', function(chunk) {
      body += chunk;
    });
    req.on('end', function() {
      var data = qs.parse(body);
      // now you can access `data.email` and `data.password`
      res.writeHead(200);
      res.end(JSON.stringify(data));
    });
  } else {
    res.writeHead(404);
    res.end();
  }
});

server.listen(80);

For multipart/form-data forms you're going to be better off using a third party module because parsing those kinds of requests are much more difficult to get right.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.