结构项目结构如下
代码如下
功能【router.js】
// 加载所需模块var http = require('http');var url = require('url');var fs = require('fs');var host = '127.0.0.1';var port = 8080; http.createserver(function(req,res){var pathname = url.parse(req.url).pathname; console.log('request for ' + pathname + ' received.');function showpaper(path,status){var content = fs.readfilesync(path); res.writehead(status, { 'content-type': 'text/html;charset=utf-8' }); res.write(content); res.end(); }switch(pathname){//'首页'case '/':case '/home': showpaper('./view/home.html',200);break;//'about页'case '/about': showpaper('./view/about.html',200); break;//'404页'default: showpaper('./view/404.html',404);break; } }).listen(port, host);
【404.html】
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>document</title> </head> <body> 404 </body> </html>
【about.html】
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>document</title> </head> <body>about </body> </html>
【home.html】
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>document</title> </head> <body>home </body> </html>
演示
以上就是nodejs实现路由功能实例详解的详细内容。
