Javascript

nodejs--重构路由小案例

本文主要是介绍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--重构路由小案例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!