Bernardo Dal Corno
Bernardo Dal Corno

Reputation: 2088

Submit/POST form data in JSON via ajax and jQuery to a Node.js webserver

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.

Upvotes: 0

Views: 1988

Answers (2)

Bernardo Dal Corno
Bernardo Dal Corno

Reputation: 2088

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
    };
  });
});

Upvotes: 1

josh3736
josh3736

Reputation: 144912

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.

Upvotes: 1

Related Questions