zoukankan      html  css  js  c++  java
  • nodejs 中,通过路由读取html页面,并在客户端显示出来

    1、html页面代码:

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8" />
    <title></title>
    <style type="text/css">
    *{
    margin: 0;
    padding: 0;
    }
    ul li{
    float: left;
    200px;
    height: 50px;
    text-align: center;
    list-style: none;
    border: 0.1px solid #000;
    line-height: 50px;
    color:#fff;
    }
    .red{
    background: red;
    }
    .blue{
    background: blue;
    }
    .green{
    background: green;
    }
    </style>
    </head>
    <body>
    <ul>
    <li class="red">1</li>
    <li class="blue">2</li>
    <li class="green">3</li>
    </ul>
    </body>
    </html>

    2、nodejs 代码:

    ************************创建服务器**************************

    var http=require("http");
    var url=require("url");
    var router=require("./02.js")
    http.createServer(function(req,res){
    if(req.url!="/favicon.ico"){
    console.log("33")
    console.log(req.url)
    pathname=url.parse(req.url).pathname;
    pathname=pathname.replace(///,"");
    try{
    console.log("22")
    router[pathname](req,res);
    console.log(pathname);
    console.log("00")
    }catch(e){
    console.log("11")
    console.log(e)
    }
    }
    }).listen(8000);
    console.log("server running at http://127.0.0.1:8000/")

    **********************************路由控制器并显示在客户端**************************************

    var optfile=require("./03.js")
    module.exports={
    login:function(req,res){
    res.writeHead(200,{"Content-Type":"text/html",charset:'utf-8'});

    function recall(data){
    res.write(data);
    res.end("");
    }
    optfile.readfile("index.html",recall);
    }
    }

    **************************************异步读取文档***********************************************

    var fs=require("fs");
    module.exports={
    readfile:function(path,recall){
    fs.readFile(path,function(err,data){
    if(err){
    console.log("不对");
    recall("没有找到页面!");
    }else{
    console.log(data.toString());
    recall(data);
    }
    })
    }
    }

    3、注意事项:

    ①通过路由控制器跳转:

      pathname=url.parse(req.url).pathname;
      pathname=pathname.replace(///,"");

      router[pathname](req,res);

      避免二次运行,添加一个if判断(if(req.url!="/favicon.ico"));

    ②当读取的html页面带有src等链接时,程序会自动再次请求服务器,进行运行!

  • 相关阅读:
    MFC 简介
    C++使用thread类多线程编程
    C++中stack
    C++中头文件简介(stdio.h & chrono)
    别人写的很好Arduino教材
    Communicating to 2 SPI Slaves with USART & SPI ports on Atmega16U2
    HDU 2089 不要62(挖个坑=-=)
    HDU 3555 Bomb(数位DP)
    HDU 3480 Division(斜率优化+二维DP)
    HDU 3045 Picnic Cows(斜率优化DP)
  • 原文地址:https://www.cnblogs.com/pyj63/p/8042068.html
Copyright © 2011-2022 走看看