Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs express, ajax posting w/ jquery and receiving response

Having some trouble getting express to respond properly to my jquery ajax request. The actual posting is working fine, but no matter what I try I cant seem to actually get a data response from my app that I can use. At first it was just posting and hanging constantly, and like a minute later it would respond with an alert that said something like "XML Document loaded" (have no idea where it was coming from) -- Anyways, now its giving me

SyntaxError: Unexpected token ILLEGAL at parse (native) at IncomingMessage.

In my express App, I have:

    app.post('/save', function(req, res) {
      console.log(req.body.objectData);
      res.contentType('json');
      res.send({ some: 'json' });
    });

and in my jquery:

  $.ajax({
    url: "/save",
    type: "POST",
    dataType: "json",
    data: {objectData: someObject},
    contentType: "application/json",
    cache: false,
    timeout: 5000,
    complete: function() {
      //called when complete
      console.log('process complete');
    },

    success: function(data) {
      console.log(data);
      console.log('process sucess');
   },

    error: function() {
      console.log('process error');
    },
  });
like image 236
thrice801 Avatar asked Jun 09 '11 07:06

thrice801


2 Answers

You are not sending a valid JSON response but a String containing the word json therefore the JSON.parse() is failing on the client side. Try this:

app.post('/save', function(req, res) {
  console.log(req.body.objectData);
  res.contentType('json');
  res.send({ some: JSON.stringify({response:'json'}) });
});

JavaScript Object Notation is a way to share data between applications in object format. However, you cannot send an object over an HTTP request without first turning it into a string and sending it as a single variable. The functions JSON.parse() and JSON.stringify() do this for us.

like image 103
Pastor Bones Avatar answered Oct 15 '22 11:10

Pastor Bones


Pastor Bones' comment was particularly important to me, as I was using $.ajax to post to a Node server. My relevant portion of code ended up like this:

// Incoming parameter "teams" is an array of objects
function saveTeams(teams) {
    var xhr;
    var data = JSON.stringify({ teams: teams });

    xhr = $.ajax({
        type: "POST",
        url: "http://localhost:8000/saveteam",
        contentType: "application/json",
        data: data,
        headers: {
            Authorization: "..."
        }
    });

    return xhr;
} 

Note that the contentType header is relevant for the parsing to work.

On the node server side, I can process the payload like this:

saveTeams: function (req, res, next) {
    var teams = req.body.teams;

    if (teams.length > 0) {
        console.log("Teams to be added:");
        for (var i = 0; i < teams.length; i++) {
            console.log(teams[i]);
            // ...
        }
    }
    // ...
}
like image 22
CLO Avatar answered Oct 15 '22 11:10

CLO