Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
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);