Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 3. Interaction with the Client > Responding to Asynchronous Requests

3.4. 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);

					  


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial