Peter Wone
Peter Wone

Reputation: 18755

Obtain payload of post

I've used jQuery to ajax post some data to a nodejs webserver.

The webserver code receives the post but I don't know how to retrieve the payload, and the nodejs documentation web is just awful. I've tried dumping the request object to the debugger console but I can't see the data there. How do I access the payload of a post?

The documentation says the request object is an instance of http.IncomingMessage and exposes a data event with the signature function (chunk) { } where chunk is either a string or a Buffer, but if you don't know where or how you're supposed to hook up to this event, or how to use a Buffer then this isn't terribly helpful.


I notice that there is a second, more narrative manual hidden under "community" rather than the "docs" link. This is good. It is currently not available. This is not so good.


I have been asked whether I'm using a framework or trying to do it "native". Ignorance prevents me from answering directly, so instead here is the code

var http = require('http');
var fs = require('fs');
var sys = require('sys');
var formidable = require('formidable');
var util = require('util');
var URL = require('url');

var mimeMap = { htm : "text/html", css : "text/css", json : "application/json" };

var editTemplate = fs.readFileSync("edit.htm").toString();

http.createServer(function (request, response) {

  request.addListener('data', function(chunk){
    console.log('got a chunk');
  });

  var body, token, value, mimeType;
  var path = URL.parse(request.url).pathname;

  console.log(request.method + " " + path);

  switch (path) {
    case "/getsettings":
      try {
        mimeType = "application/json";
        body = fs.readFileSync("/dummy.json");
      } catch(exception) {
        console.log(exception.text);
        body = exception;
      }
      //console.log(body.toString());
      break;  
    case "/setsettings":
      console.log(request); //dump to debug console
      //PROCESS POST HERE
      body = ""; //empty response
      break;  
    case "/": 
      path = "/default.htm";
      mimeType = "text/html";
    default:
      try { 
        mimeType = mimeMap[path.substring(path.lastIndexOf('.') + 1)];
        if (mimeType) {
         body = fs.readFileSync(path);
        } else {
          mimeType = "text/html";
          body = "<h1>Error</h1><body>Could not resolve mime type from file extension</body>";
        }
      } catch (exception) {
        mimeType = "text/html";
        body = "<h1>404 - not found</h1>";
      }
      break;
  }
  response.writeHead(200, {'Content-Type': mimeType});
  response.writeHead(200, {'Cache-Control': 'no-cache'});
  response.writeHead(200, {'Pragma': 'no-cache'});
  response.end(body);  
}).listen(8124);

console.log('Server running at http://127.0.0.1:8124/');

Now I have added this

request.addListener('data', function(chunk){
  console.log('got a chunk');
});

to the start of the success function for createServer. It seems to work like this, which I suppose means the success function is called prior to the listeners. If this is not the correct place to bind then someone please tell me.

Upvotes: 3

Views: 8425

Answers (1)

generalhenry
generalhenry

Reputation: 17319

Over at "//PROCESS POST HERE" add a req.pipe(process.stdout); it will output the post data to the console.

You can also pipe it to a file req.pipe(fs.createWriteStream(MYFILE)) or even back out to the browser req.pipe(res);

See an example here: http://runnable.com/nodejs/UTlPMl-f2W1TAABS

You can also add your own handlers to the events, data, error and end

var body = '';

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

request.addListener('error', function(error){
  console.error('got a error', error);
  next(err);
});

request.addListener('end', function(chunk){
  console.log('ended');
  if (chunk) {
    body += chunk;
  }
  console.log('full body', body);
  res.end('I have your data, thanks');
});

Oh and as to the 'native or module' question, you could use a module like express which will parse the body for you, and populate req.body with the result (skipping the addListener pain and even parsing formdata or json for you). See http://expressjs.com/api.html#req.body

Upvotes: 3

Related Questions