Is it possible to do form authentication/validation with pure Node.js?

Asked

Viewed 842 times

5

Today I became interested in Node.js for being able to program javascript in the back-end and front-end.

From what I understand - correct me if I’m wrong - Node is a platform that allows me to create server-side applications using Javascript.

Looking for tutorials on how to rescue data from a form or how to authenticate a user, I only found results using Express or another framework.

Is it possible to do this with pure Node? I searched the Node documentation but found nothing related.

  • I usually use this Validator: https://www.npmjs.com/package/node-validator

1 answer

4


The most common way is using the Express and one of its plugins Bodyparser to convert a form for example into an easy-to-work object.

Taking into account that both are written in Javascript it is possible to do with native code, ie "re-invent the wheel". I advise against. The concept of Node is to go to npm fetch all the modules needed to make the code easier to write, since it is a server the performance to load that modules is irrelevant as they load before starting the server.

But to answer your question here:

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

    console.dir(req.param);
    console.log(req.method);
    var body = '';
    req.on('data', function (data) {
        body += data;
        console.log("Partial body: " + body);
    });
    req.on('end', function () {
        console.log("Body: " + body);
        // aqui podes usar o body, com
        var dados = JSON.parse(body);
        // etc...
        // enviar a resposta para o browser:
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end('post received'); // ou outra mensagem de validação
    });
});

port = 3000;
host = '127.0.0.1';
server.listen(port, host);
console.log('Listening at http://' + host + ':' + port);
  • have how you put an example with a real server?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.