O'Reilly logo

Node for Front-End Developers by Garann Means

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 middleware that ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required