node.js路由入门

route的功能: 通过分析URL路径,分发到相应的控制器中, 一个路由对应的是一个或多个负责请求调用的js文件,主要处理包括业务逻辑、请求的拦截、捕获、处理
简单的路由分发分为3个部分
  • 1.创建一个简单的http服务
  • 2.创建路由的处理方法,对于不同的路径请求给予不同的数据返回
  • 3.根据不同的路径,分发不同的处理后的内容
创建一个简单的http服务
const http = require("http");
const url = require("url");
function start(route, handle) {
    function onrequest(request, response) {
        response.writeHead(200, {
            "Content-Type": "text/plain"
        })
        let postdata = {
            name: "lijia",
            age: 19
        }
        var pathname = url.parse(request.url).pathname
        route(handle, pathname, response, postdata)
    }
    http.createServer(onrequest).listen(2000)
}
创建路由的处理方法,对于不同的路径请求给予不同的数据返回
function route(handle, pathname, response, postdata) {
    if (typeof handle[pathname] == "function") {
        handle[pathname](response, postdata)
    } else {
        response.writeHead(404, {
            "Content-Type": "text/plain"
        });
        response.write("404 Not Found")
        response.end()
    }
}
根据不同的路径,分发不同的处理后的内容
let handle = {};
handle['/'] = one;
handle['/one'] = one;
handle['/two'] = two;
start(route, handle)
根据不同的路径返回不同的html内容
function one(response, data) {
    let body = `<html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <body> <a href = "/two" >two</a></body></head></html>`
    response.writeHead(200, {
        "Content-Type": "text/html"
    })
    response.write(body);
    response.end()
}

function two(response, data) {
    let body = `<html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <body><a href = "/one" >one</a></body></head></html > `
    response.writeHead(200, {
        "Content-Type": "text/html"
    })
    response.write(body)
    response.end()
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值