本篇文章给大家介绍一下使用Node实现较复杂应用路由功能的方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。
/2021/03/f42a6aa6.jpg
相关推荐:《nodejs 教程》
结构
项目结构如下
/2021/03/6fd4b019.png" alt="
代码如下
/2021/03/a3e3db98.png" alt="
功能
【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> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> 404 </body> </html>
【about.html】
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> about </body> </html>
【home.html】
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> home </body> </html>
演示
/2021/03/190d8f1c.png" alt="
/2021/03/0db4396e.png" alt="
/2021/03/6fd4b019-1.png" alt="
/2021/03/bed23ad9.png" alt="
更多编程相关知识,请访问:编程视频!!
以上就是使用nodejs实现路由功能的详细内容,更多请关注北冥有鱼其它相关文章!
本文转载自【PHP中文网】,希望能给您带来帮助,苟日新、日日新、又日新,生命不息,学习不止。