response.end() doesn't seem to be firing after node operation

I have a page with two text areas, and I want to submit the data from one of them to node (using ajax), node then does some processing, and then returns the response which is then populated into the second text area.

The console log shows that the node code is working fine it gets to res.end() but the ajax keeps reporting an Error or a TimeoutError, instead of invoking the success callback method.

The key parts of the code are:

frontend

<script>
      function processClick() {

          var data = {};
          data.topic = document.getElementById("topic").value;
          data.message = document.getElementById("request_area").value;

         $.ajax({
              url: 'http://localhost:8888/',
              dataType:'json',
              type: 'POST',
              data: JSON.stringify(data),
              timeout: 2000,
              success: function(data) {
                   $("#response_area").append(data);                            
              },
              error: function(jqXHR, textStatus, errorThrown) {
                   $("#response_area").append('[Error[textstatus=' + textStatus + ',errorThrown=' + errorThrown + ']]');
              }
         });
      }

</script>

Node

var port = 8888;
var http = require('http');


http.createServer(function (req, res) {
    response = null;
    console.log('request received');
    res.writeHead(200, {'Content-Type': 'application/json'});

    res.end('{a:"b"}');

}).listen(port);

console.log("listening on " + port);

I've stripped out most of what node does, and tried to get it just to return a json string {a:"b"} but that too results in errors. Am I messing up the content types? How much of an impact would that have?

Any help would be appreciated.

The way you are making request is actually a cross domain request and violating same origin policy, therefore the jQuery ajax calls are failing. To get this working cross-domain you should use JSONP based format.

For example node.js code:

var port = 8888;
var http = require('http');


http.createServer(function (req, res) {
    response = null;
    console.log('request received');
    res.writeHead(200, {'Content-Type': 'application/json'});
    res.end('_testcb(\'{"a": "b"}\')');

}).listen(port);

console.log("listening on " + port);

and the client side javascript should be like this

<script>
      function processClick() {

          var data = {};
          data.topic = document.getElementById("topic").value;
          data.message = document.getElementById("request_area").value;

         $.ajax({
              url: 'http://localhost:8888/',
              dataType:'jsonp',
              type: 'POST',
              jsonpCallback: "_testcb",
              data: data,
              success: function(data) {
                   $("#response_area").append(data);                            
              },
              error: function(jqXHR, textStatus, errorThrown) {
                   $("#response_area").append('[Error[textstatus=' + textStatus + ',errorThrown=' + errorThrown + ']]');
              }
         });
      }

</script>

The best way to do this within same domain is by using express. If you have to do this in pure nodejs without using express framework then you can check out the below link.

http://stackoverflow.com/a/6012543/517525

This also gives you detailed explanation about your query.

Your JSON string is invalid. The keys need to be quoted:

{"a":"b"}

Or:

JSON.stringify({a: 'b'})