0

This must be a simple question and I'm failing to see where is the error, so after reading and trying a lot of things and no advances, I surrender to ask for help!

HTML

...
<form id="FichaCadastral" method="POST">
  <input id="CPF" type="text">
  ...
  <input type="submit" value="Submit">
</form>
...

JavaScript

$(function () {
  $('#FichaCadastral').on('submit', function (e) {
    var opa = {id: 3}; //Simple test data

    $.ajax({
      url: $(location).attr('pathname'), //I just want to know what webpage posted data
      method: 'POST',
      type: 'POST',
      data: JSON.stringify(opa),
      processData: false,
      dataType: 'json', 
      contentType: 'application/json; charset=utf-8',
    }); //No success/done/fail callbacks for now, I'm focusing on this problem first

    e.preventDefault();
  });
}

Node.js

...
server = http.createServer();
server.on('request', function (request, response) {
  if (request.method === 'POST') console.log(request.body); //shows 'undefined' in node-dev console
});

I don't know in which code above is the error, because I'm new in all of them.

Bernardo Dal Corno
  • 1,858
  • 1
  • 22
  • 27
  • Where do you reference the JavaScript? Some part of the HTML that wasn't included? – Tomty Nov 26 '14 at 00:53
  • Also, you might want to take a look at http://stackoverflow.com/a/12007627/3412775 – Tomty Nov 26 '14 at 00:57
  • @Tomty yes, I referenced in the head jQuery and page-specific js. Thanks for the link! It helped me a lot, there are a lot of similar questions but none that had a complete answer like that one – Bernardo Dal Corno Nov 27 '14 at 02:04

2 Answers2

1

By default, node does not process entity bodies (the POST data). Rather, the raw bytes are emitted as data events. You are responsible for parsing the request stream.

I'd recommend just using Express and the body-parser middleware on your server.


Also,

url: location.pathname

location is a regular JavaScript object. There is no need to wrap it in jQuery.

josh3736
  • 139,160
  • 33
  • 216
  • 263
  • thanks. I'm not using Express or body-parser to learn how everything works, but sure, it would be a lot more easy. About jQuery, don't remember why I did it this way, any would do. – Bernardo Dal Corno Nov 27 '14 at 02:19
1

Just to give a complete answer without using Express or body-parser, here's the new code that I'm using and its working:

Node.js

...
server = http.createServer();
server.on('request', function (request, response) {
  ...
  var data = '';
  request.on('data', function (chunk) {
    data += chunk;
  });
  request.on('end', function () {
    if (data) {  //data shows '{"id":3}' in node-dev console
      if (request.method === 'POST') response = sPOSTResponse(request, data, response);
      //calls a method for controling POST requests with data captured
    };
  });
});
Bernardo Dal Corno
  • 1,858
  • 1
  • 22
  • 27