20210817关于nodejs express的前后端知识点梳理

参考大神链接:https://how2j.cn/k/nodejs/nodejs-router/1763.html

1.nodejs 路由-

server.js 的问题

首先回顾一下前面 server.js 的代码, 这个代码很清爽,也很容易维护。 但是当业务开始略微复杂的时候,怎么办呢?
比如业务上需要通过访问 /listCategory 显示所有的分类,又需要通过访问 /listProduct 显示所有的产品,那么仅仅通过一个 service(request, response) 方法来进行维护不是很麻烦吗
所以在这个时候,就会引入路由的概念了。

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) 函数里做的。

那么引入路由的概念的话,就是指访问 /listCategory 路径,会访问 listCategory函数。 而访问 /listProduct 路径,就会访问 listProduct 函数,这样子维护起来就容易多了。

如代码所示,会提供 listCategory() 函数。
再如图所示,访问地址 /listCategory 就会显示 listCategory() 函数的返回值。
注: 这里的代码仅仅是片段,接下来才会给出完整的代码

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值