zoukankan      html  css  js  c++  java
  • 使用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同步读取文件内容的方法,再写到页面中的方法进行路由的转换,结果如下:

  • 相关阅读:
    event的属性
    dom三个事件
    setInterval和setTimeout定时器
    eclipse编码格式设置
    eclipse Subversion Native Library Not Available
    NET Framework V4.0.30319
    eclipse配置tomcat
    eclipse Multiple annotations found at this line
    eclipse安装svn插件
    eclipse安装maven
  • 原文地址:https://www.cnblogs.com/mmykdbc/p/8334116.html
Copyright © 2011-2022 走看看