Really silly question about behavior of var req=http.request(), req.write() and req.end() in a POST request

69 views
Skip to first unread message

q2dg2b

unread,
Aug 17, 2014, 5:34:51 AM8/17/14
to nod...@googlegroups.com
Hello friends

I want to send URL-encoded data via POST to a public server (http://www.posttestserver.com , do you knew it?)

If I do: curl -X POST -H "Content-Type":"application/x-www-form-urlencoded" -d "key1=value1" http://www.posttestserver.com/post.php , it works perfectly

But if I execute this code, it doesn't send anything:

var http = require("http")
var qs = require("querystring")
var data = { key1:"value1" }
var request = { hostname: "www.posttestserver.com", path:"/post.php", method: "POST", headers: {"content-type":"application/x-www-form-urlencoded"} }
var req = http.request(request, function(res) {   res.pipe(process.stdout)  })
req.write(qs.stringify(data))
req.end()


WHY???

Thanks!!




mscdex

unread,
Aug 17, 2014, 6:12:06 PM8/17/14
to nod...@googlegroups.com
On Sunday, August 17, 2014 5:34:51 AM UTC-4, q2dg2b wrote:
WHY???


Your code isn't wrong, the server you're testing with just doesn't seem to support `Transfer-Encoding: chunked`, since if you set a Content-Length, it works fine.

q2dg2b

unread,
Aug 20, 2014, 2:50:52 PM8/20/14
to nod...@googlegroups.com
YES!!! You were right!!!

Thanks a lot!!

I've changed the code like this and now it works!! Thanks!!


var http = require("http")
var qs = require("querystring")
var data = { key1:"value1" }
var dataQS = qs.stringify(data)

var request = { hostname: "www.posttestserver.com", path:"/post.php", method: "POST", headers: {"content-type":"application/
x-www-form-urlencoded", "content-length": Buffer.byteLength(dataQS)} }

var req = http.request(request, function(res) {   res.pipe(process.stdout)  })
req.write(dataQS)
req.end()





Reply all
Reply to author
Forward
0 new messages