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()
}