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

原文地址:https://www.cnblogs.com/j-liu3323/p/8037011.html