参考大神链接:https://how2j.cn/k/nodejs/nodejs-router/1763.html
1.nodejs 路由-
server.js 的问题 |
首先回顾一下前面 server.js 的代码, 这个代码很清爽,也很容易维护。 但是当业务开始略微复杂的时候,怎么办呢? |
var http = require('http');
function service(request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello Node.js');
}
var server = http.createServer(service);
server.listen(8088);
路由概念 |
如果没有路由的概念,那么无论是访问/listCategory路径 还是访问 /listProduct 路径,都是在service(request,response) 函数里做的。 |
function listCategory() {
return "a lot of categorys";
}
function listProduct() {
return "a lot of products";
}
访问:(前提本地cmd 开启node)
http://127.0.0.1:8088/listCategory
http://127.0.0.1:8088/listProduct
分析:
为了达到前面的路由效果,需要多个模块协同配合达到这个效果。 所谓的多个模块,其实就是多个.js文件里的多个函数互相配合。 |
业务处理模块 requestHandlers.js |
首先是业务处理模块 ,即提供 listCategory函数和listProduct()函数 |
function listCategory() {
return "a lot of categorys";
}
function listProduct() {
return "a lot of products";
}
exports.listCategory = listCategory;
exports.listProduct = listProduct;
路由模块 router.js |
router函数第一个参数 handle 是一个数组,第二个参数是 路径。 |
function route(handle, pathname) {
if (typeof handle[pathname] === 'function') {
return handle[pathname]();
} else {
return pathname + ' is not defined';
}
}
exports.route = route;
服务器模块 server.js |
这个就是启动服务器的模块,同样的。。。还是要结合后面的代码来看 |
var http = require("http");
var url = require("url");
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
var html = route(handle, pathname);
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(html);
response.end();
}
http.createServer(onRequest