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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With