Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to read POST data with node.js without using express or connect

Tags: false json object

How to read POST data with node.js without using express or connect

Problem

Edit

Make sure you don't juxtapose the request and response objects. things will be easier if you dont.

I am trying to POST data from a form with two inputs to a specific url node responds to. Originally I was using the javascript xmlHTTPrequest Object to send it. The data was received but node could never read the object I tried sending which was Json format. Here is what it looked like when I converted it to a string:

{ output: [], 
  outputEncodings: [],
  writable: true,
  _last: false,
  chunkedEncoding: false,
  shouldKeepAlive: true,
  useChunkedEncodingByDefault: true,
  _hasBody: true,
  _trailer: '',
  finished: false,
  socket: 
   { _handle: 
      { writeQueueSize: 0,
        socket: [Circular],
        onread: [Function: onread] },
     _pendingWriteReqs: 0,
     _flags: 0,
     _connectQueueSize: 0,
     destroyed: false,
     errorEmitted: false,
     bytesRead: 8442,
     bytesWritten: 1669569,
     allowHalfOpen: true,
     writable: true,
     readable: true,

This was not the full string. I switched over to use an ajax post request instead because I thought serializearray() might create a different format that node could read but it was the same. My server side code is essentially just:

function email(request, response)
  form = '';
  request.setEncoding("utf8");
  request.on('data', function(chunk) {
    console.log('data received');
    form += chunk.toString();
  });

  request.on('end', function() {
    console.log('done receiving post data');
  });

My form looks like this

  

If I try parsing with JSON.parse, there is an error caused by unexpected o
If I try parsing with querystring, it returns an empty object
If I try something like console.log(form.address) the output is undefined but should be one of the values i submitted in the form.

my http server would route to /email and this is the function that responds to /email.

I checked and I know the on 'data' event has not expired because my code is set up to notify me of a 'data'event and I can see the event happening. Locally, this code works fine and I can read the data submitted but on the development server it just doesn't work.

I know people will say I should be using connect or express but let's just suppose that was not an option, how could I get node to correctly process this data? The jquery that submits the form is more or less standard. Many thanks!

EDIT:

Sorry, I thought the problem would be fixed as I noticed immediately the posted string was not JSON. Here is the code I am using to send the post.

$(document).ready(function() {
  $("#email").submit(function(event) {
  event.preventDefault();
  var data = $(this).serializeArray();
  $.ajax({
    type: 'POST',
    dataType: 'json',
    url: '/email',
    data: JSON.stringify(data),
    success: function(msg) {
    $("#aviso").html(msg);
    }
    });
  });
}); 

Here is the string the data variable holds:

[
  {
    "name": "address",
    "value": "[email protected]"
  },
  {
    "name": "honeypot",
    "value": "irobot"
  }
]

This is valid JSON as per jsonlint. But still the same error when it reaches the server. Node handles the 'data' event and all is well until I try to parse the string, it causes an error undefined:1 unexpected o.

Problem courtesy of: T. T.

Solution

The data you're sending is not valid JSON, which requires that all object keys are double-quoted.

Solution courtesy of: Matt Ball

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How to read POST data with node.js without using express or connect

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×