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

5

Today I was interested in Node.js because I could program javascript on the backend 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 retrieve data from a form or how to authenticate a user, I only find results using Express or another framework.

Is it possible to do this with pure Node? I searched the Node documentation but did not find anything related.

    
asked by anonymous 08.12.2015 / 02:05

1 answer

4

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

Given that both are written in JavaScript it is possible to do with native code, ie "re-invent the wheel". I advise against it. The concept of Node is to go to npm to find all the modules you need to make the code easier to write, since it is about of a server the performance to load these modules is irrelevant because they load before starting the server.

But answering your question here is:

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);
    
08.12.2015 / 07:29