nodeJS實現路由功能


前面的話

  本文將使用NodeJS實現較復雜應用的路由功能

 

結構

  項目結構如下

  代碼如下

 

功能

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

 

演示

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM