nodejs--重构路由小案例

在实际的开发场景中,我们需要根据不同的地址返回不同的数据,也就是我们日常所说的路由效果 

index.js:

// 入口
var server = require("./server.js");
var handler = require("./handler");
var route = require("./router.js")


var handle = {};
handle["/"] = handler.home
handle["/home"] = handler.home
handle["/user"] = handler.user
handle["/list"] = handler.list

server.startServer(route, handle);

handle.js:

//引入
var fs = require("fs");
var data = require("./data.js")

// / /home
function home(response) {
    response.writeHead(200, { "Content-Type": 'text/html' });
    fs.createReadStream(__dirname + "/home.html", "utf8").pipe(response)
}

// /user
function user(response) {
    response.writeHead(200, { "Content-Type": 'application/json' });
    response.end(JSON.stringify(data))
}

// list
function list(response) {
    response.writeHead(200, { "Content-Type": 'application/json' });
    var lists = [{
            name: "iwen"
        },
        {
            name: "ime"
        }
    ]
    response.end(JSON.stringify(lists))
}

module.exports = {
    home,
    user,
    list
}

server.js:

var http = require("http");

function startServer(route, handle) {
    //创建服务器
    var server = http.createServer(function(request, response) {
        //
        route(handle, request.url, response)
    })

    //服务器监听
    server.listen(3000, "127.0.0.1");
    console.log("服务器运行在3000端口上");
}

//导出
module.exports = {
    startServer
}

router.js:

var fs = require("fs");

function route(handle, pathname, response) {
    if (typeof handle[pathname] === 'function') {
        handle[pathname](response);
    } else {
        response.writeHead(404, { "Content-Type": 'text/html' });
        fs.createReadStream(__dirname + "/404.html", 'utf8').pipe(response);
    }
}

module.exports = route;

data.js:

var data = {
    name:"iwen",
    age:20
}

module.exports = data;

nodejs--重构路由小案例

nodejs--重构路由小案例

nodejs--重构路由小案例

nodejs--重构路由小案例

上一篇:nodejs--GET方式发送数据


下一篇:handler面试准备