How to get POST input in Node.js?

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

I am trying to figure out how I can get POST data from every single input.

I am making a login system:

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

Thus, the user enters the login and POST ed input 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 may console.log the body. For example, this will be console.log mail data as follows:
email=emailaddy@gmail.com password = thisismypw

BUT, how can I get the input separately? I think in PHP I could target every input this way:

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

and I could put these values ​​in a variable and use them for INSERT or CHECK for the database.

Can someone please show me how I can do this in Node.js? Please do not use any bean modules!

+6
source share
1 answer

For application/x-www-form-urlencoded forms (default), you can usually just use the querystring parser for 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 will be better off working with a third-party module, because parsing these requests is much more complicated.

+9
source

Source: https://habr.com/ru/post/976831/


All Articles