nodejs--GET方式发送数据

2021/8/5 9:35:55

本文主要是介绍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方式发送数据的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程