Site icon Teaching Newbies since 2014

Assembling request handlers for the router in your node.js server

It’s been a long time since I did one of these, I’ve just been too busy with tinkering with JS which is turning out to be my favorite language. This is again from the nodebeginner book by Manuel Kiessling.

Anyways after assembling your router,it must route specific requests to their appropriate destinations. In this case the requests such as start and upload  are routed to request handlers. Mindless analogy: if cars and trucks are requests then the router is like a road and the request handlers like toll booths which collect the appropriate fare from cars, trucks etc.

1) Create a requestHandler.js file

2) Fill with this code:

function start() {

console.log("Request handler 'start' was called");

}

function upload() {

console.log("Request handler'upload' was called);

}

exports.start =start;

exports.upload=upload;

2) Now modify the index.js file:

var server = require("./server");

var router = require("./router");

var requestHandlers = require("./requestHandlers");

var handle = {}

handle["/"] = requestHandlers.start;

handle["/start"]= requestHandlers.start;

handle["/upload"] = requestHandlers.upload;

server.start(router.route, handle);

3) Following on the same trend, the server.js file must be changed:

var http = require("http");

var url = require("url");

function start (route, handle) {

function onRequest (request, reponse) {

var pathname = url.parse(request.url).pathname;

console.log("Request for" + pathname + "received");

route( handle, pathname);

response.writeHead(200, {"Content-Type": "text/plain"});

response.write("Hello World");

response.end();

}

http.createServer(onRequest).listen(8888);

console.log("Server has started");

}

exports.start = start;

4) Modify the router.js file:

function route(handle, pathname) {

console.log("About to route a request for" + pathname);

if typeof handle[pathname] === 'function') {

handle[pathname] ();

} else {

console.log("No request handler found for" + pathname);

return "404 not found";

}

}

exports.route = route;
Exit mobile version