Fabien Papet
Fabien Papet

Reputation: 2319

NodeJS get posted data - No framework

Assuming I would like to get posted data into a variable in /completed case. How do I have to do ? I am able to retrieve data into request.on("data" ...) but if I log data into my /completedcase, data is empty.

var http = require('http');
http.createServer( function(request, response) {
    var data = "";
    if(request.method == 'POST') {
        request.on('data', function(chunk) {
            console.log('Received data:', chunk.toString());
            data += chunk.toString();
        });
        request.on('end', function() {
            console.log('Complete data:', data);
        });
    }
    switch (request.url) {
        case "/":
            response.writeHead(200, {'Content-Type': 'text/html'});
            response.write("<a href='/form'>Go to form</a>");
            response.end();
            break;
        case "/form" :
            response.writeHead(200, {'Content-Type': 'text/html'});
            response.write("<form method='POST' action='/completed'>");
            response.write("<input type='text' name='data1'/><hr/>");
            response.write("<input type='text' name='data2'/><hr/>");
            response.write("<input type='text' name='data3'/><hr/>");
            response.write("<input type='file' name='data4'/><hr/>");
            response.write("<input type='submit' value='Send'/>");
            response.end("</form>");
            break;
        case "/completed":
            console.log(request);
            response.writeHead(200, {'Content-Type': 'text/html'});

            // var post = ?

            response.end();
            break;
        default:
            response.writeHead(403, {'Content-Type': 'text/html'});
            response.end("Forbidden");
            break;
    }

}).listen(1337);

Result

Received data: data1=dfs&data2=ds&data3=dvbcfgxrtgdw
Complete data: data1=dfs&data2=ds&data3=dvbcfgxrtgdw

Upvotes: 2

Views: 2266

Answers (1)

RobertoNovelo
RobertoNovelo

Reputation: 3810

You can:

app.use(express.bodyParser());

app.post('/completed', function(request, response){

    console.log(request.body.user.name);
    console.log(request.body.user.email);

});

Assuming you use express.

Else, you would have to use the req.on data and end events:

if (req.method == 'POST') {
    console.log("POST");
    var body = '';
    req.on('data', function (data) {
        body += data;
        console.log("Partial body: " + body);
    });
    req.on('end', function () {
        console.log("Body: " + body);
    });
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('post received');
}

You could also add:

qs = require('querystring');

var json = qs.parse(body);

util.log("json: " + json);

To retrieve the params.

Express is very helpful and I like to use it to avoid these kind of code handling.

Upvotes: 1

Related Questions