使用Node.js完成路由

首先先看一下文件的结构:

我想通过改变不同的路由进不同的页面,

先看这几个HTML页面:

404:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
404
</body>
</html>

 about:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
about
</body>
</html>

  home:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
home
</body>
</html>

  再看一下主要的root.js:

// 加载所需模块
let http = require('http');
let url = require('url');
let fs = require('fs');

let host = '127.0.0.1';
let port = 8080;

http.createServer(function(req,res){
    let pathname = url.parse(req.url).pathname;
    console.log('Request for ' + pathname + ' received.');
    function showPaper(path,status){
        let 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('./rooter/home.html',200);
            break;
        //'about页'
        case '/about':
            showPaper('./rooter/about.html',200);
            break;
        //'404页'
        default:
            showPaper('./rooter/404.html',404);
            break;
    }
}).listen(port, host);

  首先我们得到了路由的URL的pathname,然后通过pathname进行判断,这里是通过使用readFileSync同步读取文件内容的方法,再写到页面中的方法进行路由的转换,结果如下:

 

posted @ 2018-01-23 09:55  明明一颗大白菜  阅读(1935)  评论(0编辑  收藏  举报
<-- -->