3

I am just starting to play around with Node.js. I have a simple test setup.

    var sys = require('util'),
http = require('http'),
qs = require('querystring');

http.createServer(function (req, res) {

    if (req.method == 'POST') {
        var body = '';
        req.on('data', function (data) {
            body += data
        });

        req.on('end', function () {
            var POST = qs.parse(body);
            console.log(POST);
        });
    }


    res.writeHead(200, {'Content-Type': 'text/plain'});

    res.end('success');


}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');

My test client JS

 $.post("http://127.0.0.1:1337", "This is my POST data.", function (data) {
        alert(data);
    });

    $.get("http://127.0.0.1:1337", function (data) {
        alert(data);
    });

If I browse to the address where my HTTP server is running : http://127.0.0.1:1337 I see the response text, "success".

However when I use $.post or $.get they both succeed with a status of 200 but no response. The $.get and $.post callback functions are never called, and I do not see an alert appear. What am I doing wrong?

Thanks!

Nick
  • 17,810
  • 47
  • 175
  • 303
  • I'd take a look at [`.error()`](http://api.jquery.com/jQuery.post/) to see if a non-200 is coming back. – hafichuk Dec 01 '11 at 04:50
  • @hafichuk I will try that.. however firebug shows a status of 200 – Nick Dec 01 '11 at 04:52
  • 1
    Status of `200` with no response data often means same origin policy violation. You're probably hosting the client file from your filesystem? To disable security in Chrome, see: http://stackoverflow.com/questions/3102819/chrome-disable-same-origin-policy – RightSaidFred Dec 01 '11 at 05:00

1 Answers1

0

It seems to work fine for me. How are you testing?

Try with curl:

curl -XGET http://localhost:1337/

And to post:

curl -XPOST -d foo=bar http://localhost:1337/

One thing to be aware of is that how you made the code you are returning 'success' no matter what the input to the POST is. If you need to process/review the data posted first, you need to send the response after the req.on('end', ...) is called. (Or in that function).

Ask Bjørn Hansen
  • 6,099
  • 2
  • 23
  • 38
  • Thanks.. but I would expect to get an alert back. I am testing using the client code in my post. What I don't understand is why the $.get and the $.post callback functions are never called. – Nick Dec 01 '11 at 05:45
  • Show a complete example of your client then. – Ask Bjørn Hansen Dec 02 '11 at 09:24