node 构建应用模块(http请求,路由)
2017-01-06 本文已影响0人
围墙w
目标:构建一个简单的http服务器,并实现路由
文件目录
图片.png
根目录下的Index.js是主文件,把服务器模块放进server.js里,router是路由,requestHandlers是处理请求,根据url地址反馈不同的请求。
server.js
var http = require('http');
var url =require('url'); //url和http都是node.js模块
function start(route,handle) {
function onRequest(request,response) {
var pathname = url.parse(request.url).pathname;
response.writeHead(200,{'Content-Type':'text/plain'});
var content = route(handle,pathname);
response.write(content);
response.end();
}
http.createServer(onRequest).listen(80);
console.log('server running at 80');
}
exports.start = start;
把服务器脚本放到一个start的函数里,然后导出这个函数,index来调用。
- nodejs是事件驱动的,
下图是介绍url.parse和querystring的用法
图片.png
router.js
//路由文件
function route(handle,pathname) {
if (typeof handle[pathname] ==='function') {
return handle[pathname]();
}else{
console.log('no request'+pathname);
return 'NOT found';
}
}
exports.route = route;
index.js
var server = require('./server');
var router =require('./router');
var requestHandlers = require('./requestHandlers');
var handle = {};
handle['/start'] = requestHandlers.start,
handle['/upload'] = requestHandlers.upload;
server.start(router.route,handle);
我们在start函数里添加了handle参数,并且把handle作为第一个参数传递给了route()回调函数
requestHandlers.js
//处理请求
function start() {
console.log('do start');
return "start";
}
function upload() {
console.log('do upload');
return 'upload';
}
exports.start = start;
exports.upload = upload;