Vinay Verma
Vinay Verma

Reputation: 1194

Problem receiving response from node server using ajax post request

I have written a http server using node js

var sys = require("sys"),
    http = require("http"),
    url = require("url"),
    path = require("path"),
    fs = require("fs");



http.createServer(function(request, res) {

    var parsed_url = url.parse(request.url);
    var uri = parsed_url.pathname;
   if(uri === "/test"){

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

      request.addListener('data', function (chunk) {
          var data = eval("(" + chunk + ")");
          console.log(data[0].id);
      })
      request.addListener('end', function() {
          console.log('end triggered');
          res.write("Post data");
          res.end();
      }); 
   }
}).listen(8080);

and i am trying to send back response of ajax request but i am unable to receive any response. Here is the code for ajax request ,

    var myhttp = new XMLHttpRequest();
    var url = "http://localhost:8080/test";

    var data = [{"a":"1"},{"b":"2"},{"c":"3"}];

    var dataJson = JSON.stringify(data);
    myhttp.open('POST', url, true);
    myhttp.send(dataJson);
    myhttp.onreadystatechange = function() {        
        if ((myhttp.readyState == 4) && (myhttp.status == 200)){
            alert(myhttp.responseText);
        }
        else if ((myhttp.readyState == 4) && (myhttp.status != 200))
        {
            console.log("Error in Connection");
        }

Can anyone help me what i am doing wrong ...

Thanks Vinay

Upvotes: 1

Views: 4622

Answers (2)

Joao Da Silva
Joao Da Silva

Reputation: 14529

Your code is almost right but on your code sample you have

console.log(data[0].id)

the data object has no property id so if you only have

console.log(data[0])

there you have a response like

{ a: '1' }

therefore you can access the property a by doing

console.log(data[0].a);

UPDATED Updated with a full example

One more thing is that you are using eval and node comes with JSON.parse bundle with it so the snippet below is how i made it work

File: app.js

var sys = require("sys"),
    http = require("http"),
    url = require("url"),
    path = require("path"),
    fs = require("fs");



http.createServer(function(request, res) {    
   var parsed_url = url.parse(request.url);
   var uri = parsed_url.pathname;

   if(uri === "/test"){

      res.writeHead(200, {'Content-Type': 'text/javascript'});
      request.addListener('data', function (chunk) {
          // removed this - eval("(" + chunk + ")");
          var data = JSON.parse(chunk);    
          console.log(data[0].a);
      })
      request.addListener('end', function() {
          console.log('end triggered');
          res.write("Post data");
          res.end();
      });              

   } else if(uri === "/") {
       fs.readFile("./index.html",function(err, data){
         if(err) throw err;
          res.writeHead(200, {'Content-Type': 'text/html'});
          res.end(data);
       });    
   }

}).listen(8080); 

On the same directory create a file index.html with the following:

<html>
<head>
    <script type="text/javascript" charset="utf-8">
         var myhttp = new XMLHttpRequest();
       var url = "http://localhost:8080/test";

       var data = [{"a":"1"},{"b":"2"},{"c":"3"}];
       var dataJson = JSON.stringify(data);

       myhttp.open('POST', url, true);
       myhttp.send(dataJson);
       myhttp.onreadystatechange = function() {        
           if ((myhttp.readyState == 4) && (myhttp.status == 200)){
               alert(myhttp.responseText);
           }
           else if ((myhttp.readyState == 4) && (myhttp.status != 200))
           {
               console.log("Error in Connection");
           }
       }
    </script>
</head>
<body>
</body>
</html>       

That is a complete working example of what you want.

With regards to the same origin policy issues you were having is mainly due to the fact that you cant POST data between 2 different domains via ajax unless you use some tricks with iframes but that is another story.

Also i think is good for anyone to understand the backbone of a technology before moving into frameworks so fair play to you.

good luck

Upvotes: 3

schaermu
schaermu

Reputation: 13460

You have to read the data in a different way. Posted data arrives on a node server in chunks (the 'data' event), that have to be collected until the 'end' event fires. Inside this event, you are able to access your payload.

var body = '';

request.addListener('data', function (chunk) {
  body += chunk;
});

request.addListener('end', function() {
  console.log(body);
  res.write('post data: ' + body);
});

Additionaly, there seem to be some issues with your client-side code (especially concerning the status-code checks), but i can't really help you with those as i always work with frameworks like jQuery to manage async requests.

If you want to build reliable node.js servers for web use, i highly recommend the high-performance HTTP-Framework Express. It takes away alot of the pain when developing a web-based server application in node and is maintained actively.

Upvotes: 2

Related Questions