zoukankan      html  css  js  c++  java
  • node js 路由

    这是一个node js 路由的小栗子

    注意目录结构,如果用UE注意文件编码要转成UTF-8!!!

    Luyou.js

    //获取http模块
    var http = require("http");
    //文件模块
    var fs = require('fs');
    
    //主页路由模块,file文件夹里的index.js文件
    var index = require('./file/index');
    //错误处理文件路径
    var error = "./file/error404.html";
    //春晓页面路径
    var cx = "./file/chunxiao.html";
    
    //函数Response,将HTML、css、js等文件响应给客户端
    var Response = function(res,filePath){
        //读取文件,读取完成后给客户端响应
        fs.readFile(filePath,function(err,data){
            if(err){                        //如果失败,就返回错误文件
                if(filePath != error)       //如果失败的不是错误文件,才返回错误文件
                    Response(res,error);
            }else{
                res.writeHead(200,{              //响应客户端,将文件内容发回去
                    'Content-type':"text/html"});
                res.end(data);
            }
        });
    };
    //404错误响应文件
    var error404 = function(res){
       Response(res,error);
    };
    
    //创建HTTP服务器
    var server = http.createServer(function(req,res){
       console.log(req.url);               //在控制台打印请求
        //判断URL,提供不同的路由
        if(req.url == '/index' || req.url == '/') {    //主页
            index.index(res);
        }
        else if(req.url == '/chunxiao') {   //访问chunxiao.html
           Response(res,cx);
        }
        else {                              //访问其它静态文件,如*.css
            Response(res,"./file"+req.url);
        }
    });
    
    //启动服务器
    server.listen('3000',function(){
        console.log("服务器启动啦");
    });

    file文件夹下-->index.js

    exports.index = function(res){
    res.writeHead(200,{
    'Content-type':"text/html"});
    res.write('<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'
    +'水面清圆,一一风荷举。');
    res.end();
    };

    file文件夹下-->error.html

    <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <b>错误404:页面没有找到.</b> </body> </html>


    file文件夹下-->chunxiao.html

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>春晓</title>
    </head>
    <body>

    <nav>春晓</nav>
    <div id="value">
    <p>春眠不觉晓</p>
    <p>处处闻啼鸟</p>
    <p>夜来风雨声</p>
    <p>花落知多少</p>
    </div>
    </body>
    </html>

    测试方法: node Luyou.js

    在浏览器输入 http://localhost:3000/chunxiao

  • 相关阅读:
    IOptions、IOptionsMonitor、IOptionsSnapshot的区别
    基于 .NET 的 FluentValidation 验证教程
    挂载NFS网络文件系统教程
    gcc简要知识点
    二叉树遍历(前序、中序、后序、层次、广度优先、深度优先遍历)
    项目管理的一些知识总结
    Vue从零开发单页应用程序项目
    CRC校验原理
    Linux 文件搜索神器 find 实战详解
    Linux 三剑客之 grep、sed、awk 使用详解
  • 原文地址:https://www.cnblogs.com/j-liu3323/p/8037011.html
Copyright © 2011-2022 走看看