春风得意马蹄疾
一日看尽长安花

nodeJS实现路由功能

本文将使用NodeJS实现较复杂应用的路由功能

结构

项目结构如下

route1

代码如下

route2

功能

【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>

效果演示

route3
route4
route5
route6

Like
Like Love Haha Wow Sad Angry
赞(0) 打赏
未经允许不得转载:栗子纪blog » nodeJS实现路由功能
分享到: 更多 (0)
0 0 vote
Article Rating
Subscribe
提醒
guest
0 评论
Inline Feedbacks
View all comments

创作不易,打赏一下作者买瓶洗发露

支付宝扫一扫打赏

微信扫一扫打赏

0
Would love your thoughts, please comment.x
()
x