nodejs--GET方式发送数据

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);

router.js:

var fs = require("fs");

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

module.exports = route;

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,params){
    response.writeHead(200,{"Content-Type":'application/json'});
    console.log(params);
    response.end(JSON.stringify(params))
}

module.exports = {
    home,
    user,
    list
}

var http = require("http");
var url = require("url");
var querystring = require("querystring");

function startServer(route, handle) {
    var server = http.createServer(function(request, response) {
        // 拿到路径 例如:localhost:3000/list
        var pathname = url.parse(request.url).pathname;
        var params = url.parse(request.url, true).query;
        route(handle, pathname, response, params);
    })

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

module.exports = {
    startServer
}

nodejs--GET方式发送数据

 

 

上一篇:.Net学习 第2季05 C#面向对象 ArrayList


下一篇:nodejs--重构路由小案例