NodeJS之Redirect

根据模块化和松耦合的思想,一个简单的http服务器可分为server.js,redirector.js,redirectHandlers.js以及launcher.js模块。

server.js文件中是非常基础的http服务器代码。
redirector.js用于对重定向的处理。
而redirectHandlers.js是对各种重定向处理函数的封装。
launcher.js用于调用应用的其他模块(比如server.js中的http服务器模块)来引导和启动应用。

上代码:
server.js

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

function start(redirect, redirectHandle) {
function onRequest(request,response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");

var string = redirect(pathname, redirectHandle);

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

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

exports.start = start;


redirector.js

function redirect(pathname, redirectHandle) {

if(typeof redirectHandle[pathname] === 'function') {
return redirectHandle[pathname]();
} else {
console.log("Bad request for " + pathname + "page.");
return "400 Not found";
}
}
exports.redirect = redirect;


redirectHandlers.js

function index() {
console.log("Redirect to 'index' page.");
return "Hello guy!!!"
}

function what() {
console.log("Redirect to 'what' page.");
return "What can I do for you?"
}

function how() {
console.log("Redirect to 'how' page.");
return "How are you!"
}

exports.index = index;
exports.what = what;
exports.how = how;


launcher.js

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

var redirectHandle = {};
redirectHandle["/"] = redirectHandlers.index;
redirectHandle["/index"] = redirectHandlers.index;
redirectHandle["/what"] = redirectHandlers.what;
redirectHandle["/how"] = redirectHandlers.how;

server.start(redirector.redirect, redirectHandle);


Node好强大:[url=http://cnodejs.org/topic/5141fda6069911196d5c95c4]一个node做的豆瓣数据统计网站[/url]

more:
[url=http://www.nodebeginner.org/index-zh-cn.html]Node 入门[/url]

你可能感兴趣的:(NodeJS)