node.js - Simple node reading POST -
i'm trying read post data through nodejs. have following snippet of code:
var http = require("http"); console.log("server created @ 127.0.0.1:8989"); var server = http.createserver(handler).listen(8989); function handler(req,res) { console.log("client connected"); // res.writehead(200,{"content-type": "text/html"}); res.writehead(200, {'content-type': 'text/html'}); res.end('<html><body><form method="post"><input type="text" name="name"><input type="submit" value="send"></form></body></html>'); if(req.method==="post") { var body=""; console.log("post being sent"); req.on('data',function handlepost(chunck){ body+= chunck; }); req.on("end",function(){ console.log(body + "<--"); }) } }\\ however program acts if "data" event never happens? body variable never gets logged
thanks
you should make if/else. have ending request (with res.end) regardless if post or not.
function handler(req,res) { console.log("client connected"); if(req.method==="post") { var body=""; console.log("post being sent"); req.on('data',function handlepost(chunck){ body+= chunck; }); req.on("end",function(){ console.log(body + "<--"); }) } else { res.writehead(200, {'content-type': 'text/html'}); res.end('<html><body><form method="post"><input type="text" name="name"><input type="submit" value="send"></form></body></html>'); } } second example. returns form again message after post.
function handler(req,res) { console.log("client connected"); if(req.method==="post") { var body=""; console.log("post being sent"); req.on('data',function handlepost(chunck){ body+= chunck; }); req.on("end",function(){ var name = body.match(/name=(\w+)/)[1]; res.writehead(200, {'content-type': 'text/html'}); res.end('<html><body>welcome back, ' + name + '<form method="post"><input type="text" name="name" value="' + name + '"><input type="submit" value="send"></form></body></html>'); }); } else { res.writehead(200, {'content-type': 'text/html'}); res.end('<html><body><form method="post"><input type="text" name="name"><input type="submit" value="send"></form></body></html>'); } } the second example runs this... if not post, send form. if post, receive body when complete send message along form.
Comments
Post a Comment