Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get input POST data in Node.js?

Tags:

node.js

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!

like image 539
user3658794 Avatar asked Oct 16 '14 15:10

user3658794


People also ask

What is get and post method in node JS?

GET and POST both are two common HTTP requests used for building REST API's. POST requests are used to send large amount of data. Express. js facilitates you to handle GET and POST requests using the instance of express.


1 Answers

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.

like image 105
mscdex Avatar answered Oct 11 '22 16:10

mscdex