An esay way to accept GET or POST variables on a node.js server is the sample show below:
var fu = require("./fu"), sys = require("util"), url = require("url"), qs = require("querystring"); var nodemailer = require('nodemailer'); fu.get("/entrar", function (req, res) { // ------ condition to chech if call are POST o GET if(req.method=="POST") { var body=""; req.on("data", function (data) { body +=data; }); req.on("end",function(){ var variables = qs.parse(body); var pathname = url.parse(req.url).pathname; //rest of code - this function is executed when all the variables are received }); req.on("error",function(e){ //console.log('problem with request: ' + e.message); }); } else if(req.method=="GET") { var variables = url.parse(req.url, true).query; var pathname = url.parse(req.url).pathname; //rest of code - We have no wait variables like POST request } // end condition post o get return ;//"ok: });
In this case this funcion works with POST and GEt request, on the GET request case, there is no problem to get the variables with the function: url.parse(req.url, true).query;
as you can see, the trick in a POST request is the instruction: req.on( when the variables “POST” are fully recived , then req.on(“end”,function(){}) are executed.
remember that node.js is an asyncronous envirovment and the function req.on is executed after main function end.
my latest development using node.js and socket.io (Multiplayer Online Charts game): http://mp.colome.org
One thought on “GET or POST variables in node.js server”