technoweenie/node-scoped-http-client

post data does not sent

Opened this issue · 2 comments

I have this hubot-script:

module.exports = (robot) ->
  data = 'foo=lunch&dog=28'
  msg.http('http://www.example.com/echo.php')
     .post(data) (err, res, body) ->
       msg.send body

Where echo.php just returns JSON with a dump of the $_POST array

<?php

$data = array(
    'post' => $_POST);

header('Content-type: text/javascript; charset=utf-8');
echo json_encode($data);

What I get back is {"post":[]}. The data does not make it.

If I write this without using node-scoped client, I get the expected result: "post":{"foo":"lunch","dog":"28"}}

http = require('http')

module.exports = (robot) ->

  robot.respond /blargo/i, (msg) ->
    data = 'foo=lunch&dog=28'
    options =
      host: 'www.example.com',
      port: '80',
      path: '/echo.php',
      method: 'POST',
      headers:
          'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Length': data.length
    response = ''
    req = http.request options, (res) ->
      res.setEncoding 'utf8'
      res.on 'data', (chunk) ->
        response += chunk
      res.on "end", ->
        msg.send response
    req.write data
    req.end()

What am I doing wrong?

Looking at the request headers, one difference I see is that the scoped-client request has the Connection header set to close instead of keep-alive.

I am not sure it will change anything but I would suggest this:

module.exports = (robot) ->
  data = JSON.stringify
    foo="lunch"
    dog=28
  msg.http('http://www.example.com/echo.php')
     .headers("Content-Type": "application/json")
     .post(data) (err, res, body) ->
       msg.send body

and make sure to change your PHP Content Type to reflect the data type (JSON)