Node API for making HTTP requests

There is framework Express for automizing some of the things in Node.js. At the same time, sometimes its necessary to do things in native way(without Express) to be more flexible. In this post, we distinguish the differences while also listing little snippets on of how-to do different things including writing HTTP requests and reading responses

Two ways to respond HTTP Request

1) Native

  res.writeHead(200, {"Content-Type": "text/html"});
  res.write(html);
  res.end();

2) Express

        res.send({response: 'done'});

-OR-

      res.statusCode = 200;
      res.setHeader('Content-type', 'application/json; charset="utf-8"');
      res.end('OK\n');

Ways For Read HTTP Request

1) Listening Events – Native and Express the same

    var body = "";
    req.setEncoding('utf8'); //To ensure reads strings(Express does this by default)
    req.on('data', function(chunk){body += chunk});//reads the request
    req.on('end', function(){res.end('Ok\n');}//ends the request

-Or in Express already received and parsed:

exports.processReview = function(req, res){
  // the bodyParser (if it is in fact already a middleware) will have parsed
  // the request body already into `req.body`
  var review = new Review({
    title: req.body.title,
    content: req.body.content,
    submittedBy: req.body.submittedBy,
    recommendedFor: req.body.recommendedFor
  });

Ways For Routing Resources

1)Express

var express = require('express')
    , routes = require('./routes') 
    , http = require('http')
    , path = require('path')
    , api = require('./routes/api')
    , user = require('./routes/user');
    var app = express();
    ...
    app.get('/users', user.list);
    app.post('/api/cache/:id?', api.updateVersion);

2)d Native
There are probably many ways but this looks the most elegant:

var http = require("http");
var url = require("url");

var route = {   routes : {},   
    for: function(method, path, handler){     
        this.routes[method + path] = handler;   
    } 
}   

route.for("GET", "/start", function(request, response){     
    response.writeHead(200, {"Content-Type": "text/plain"});     
    response.write("Hello");     response.end();   });   

route.for("GET", "/finish", function(request, response){     
    response.writeHead(200, {"Content-Type": "text/plain"});     
    response.write("Goodbye");     
    response.end();   
});

function onRequest(request, response) {   
    var pathname = url.parse(request.url).pathname;   
    console.log("Request for " + request.method + pathname +" received.");   
    if(typeof(route.routes[request.method+pathname])==='function'){     
        route.routes[request.method + pathname](request, response);   
    }else{     
        response.writeHead(404, {"Content-Type": "text/plain"});     
        response.end("404 Not Found");   
    } } 

http.createServer(onRequest).listen(9999); 
console.log("Server has started.");

Servicing on Port

1. Express

http.createServer(app).listen(app.get('port'), 
   function(){ console.log("Express server listening on port " + app.get('port')); 
});

2. Native
???

Incorporating Client Lib such as JQuery

1. Express
One way is to do it via Jade engine
First, download the JQuery Lib into public/javascript/jquery.min.js
Next, in layout.jade add the following:

script(type='text/javascript', src='/javascripts/jquery.min.js')

Leave a Reply

Your email address will not be published. Required fields are marked *