Receiving Data from a POST
The more traditional model of getting user dataâtaking a POST
request from a formâmight not be the first thing youâd think of using Node
for, but of course itâs still necessary. In fact, handling a POST may
provide one of the most concise explanations of how Node differs from
other server setups, and how it might make more sense in the context of
the way the web actually works. The ServerRequest
object (the
req
argument in our callbacks) has no property containing the
parameters passed along in a POST, but it is an
EventEmitter. EventEmitter is the generic object type in Node for things
thatâas you might expectâemit events. Rather than looking at a property on
req
to find posted data, we add an event subscriber to listen
for it.
All EventEmitter subscribers, including the subscribers belonging to
ServerRequest
, are created by the on()
function,
which needs an event type and a callback as parameters, at minimum. (The
addListener()
function does the same thing.) The request data
will come across in chunks, so weâre not waiting to receive all of it
before other code can run. Here, weâll create listeners for the receipt of
data and the end of the request, saving all the chunks of data, but not
expecting it to be present until the request is complete:
var http = require("http"), fs = require("fs"), querystring = require("querystring"); http.createServer(function(req, res) { var data = ""; // serve static form if (req.method == "GET") { getFile(__dirname ...
Get Node for Front-End Developers now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.