日期:2014-05-16  浏览次数:20353 次

NODEJS(2)File Upload Sample with routers and handlers
NODEJS(2)File Upload Sample with routers and handlers

What's needed to "route" requests?
We need to be able to feed the requested URL and possible additional GET and POST parameters into our router, and based on these the router then needs to be able to decide which code to execute(a collection of request handlers that do the actual work when a request is received).

We need other modules in Node.js namely url and querystring.

url module provide methods which extract the URL, and querystring module for query string.

We do some changes in server.js as follow, we can get the requestpath in our URL.
var url = require("url");
...snip...
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
We get these messages on console then:
Request for / received.
Request for /luohua received.
Request for /order.do received.

We create a router.js with these content:
function route(pathname){
            console.log("About to route a request for " + pathname);   
}

exports.route = route;

Pass the function method name to our route and start, refactor server.js as follow:
function start(routeMethod) {
...snip...
routeMethod(pathname);
...snip...

index.js will be changed as follow:
var server = require("./server");
var router = require("./router");

server.start(router.route);

Execution in the kingdom of verbs
Routing to real request handlers
Create a module requestHandlers.js as follow:
function start(){
            console.log("Request handler 'start' was called.");   
}

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

exports.start = start;
exports.upload = upload;

In JavaScript, objects are just collections of name/value pairs, think of a JavaScript object as a dictionary with string keys.
We use a key/value pair, put the functions in value, and pass this map to our router.
index.js
var requestHandlers = require("./requestHandlers");

var handle = {}
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;

server.start(router.route, handle);

server.js
function start(routeMethod, handleMap) {
...snip...
routeMethod(handleMap,pathname);
...snip...

router.js
function route(handleMap,pathname){
            console.log("About to route a request for " + pathname);   
            if(typeof handleMap[pathname] === 'function'){
                        handleMap[pathname](); 
            } else {
                        console.log("No request handler found for " + pathname);
            }
}

Making the request handlers respond
How to not do it
We will write back the content in response
requestHandlers.js
function start(){
            console.log("Request handler 'start' was called.");  &nbs