Responding to Asynchronous Requests

So far, we’ve looked at ways of getting data to the server that haven’t changed much since most of us first experienced the web. More and more front-end developers these days, however, eschew those methods entirely in favor of the single-page app. Single-page apps, of course, rely on Ajax.

It’s useful to begin working with Node without the addition of niceties like frameworks and templating when it comes to handling asynchronous requests. Because we’re still pretty close to the metal, it’s easy to convert what we have from a synchronous to an asynchronous request handler. Let’s say we receive a GET request with the data in the querystring and need to provide support for JSONP:

var http = require("http"),
  querystring = require("querystring"); 
  
http.createServer(function(req, res) {
  var qs = querystring.parse(req.url.split("?")[1]),
    username = qs.firstName + " " + qs.lastName,
    json;
    
  if (qs.callback) {
    // if we have a callback function name, do JSONP
    json = qs.callback + "({username:'" + username + "'});";
  } else {
    // otherwise, just return JSON
    json = JSON.stringify({"username":username});
  }
  
  res.writeHead(200, {
    // change MIME type to JSON
    "Content-Type": "application/json",
    "Content-Length": json.length
  });
  res.end(json);
}).listen(8000);

Even if we were using some sort of abstraction on top of Node itself, we’d probably just need to change the MIME type of our response to work with asynchronous requests and responses. There’s also ...

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.