当前位置:网站首页>nodeJs--封装路由
nodeJs--封装路由
2022-08-05 02:06:00 【H5_ljy】
一、什么是路由
路由: 指不同的网址去执行不同的分支或者程序
二、封装路由
需求:前端输入网址后端返回相应的数据,首先输入网址后先去静态托管的文件夹去找;没有则去我们找数据接口,还没有则传个字符串比如“404 not found”。
**静态托管:**当用户输入网址时,我们可以在后端使用中间件在pathname的开头添加个文件夹来写入readFile的url中读取,就实现了,用户只能访问那个文件夹里面的文件。
比如:
var url=require("url")
var http=require("http")
var fs=require("fs")
http.createServer((req,res)=>{
let pathname=url.parse(req.url).pathname
fs.readFile(__dirname+'/public'+path,(err,data)=>{ // '/public'就是我们要托管的文件夹
res.end(data)
}}).listen(8080)
设计思想:根据需求,采用MVC编程思想来设计。
什么是MVC
V即View视图是指用户看到并与之交互的界面。比如由html元素组成的网页界面,或者软件的客户端界面。MVC的好处之一在于它能为应用程序处理很多不同的视图。在视图中其实没有真正的处理发生,它只是作为一种输出数据并允许用户操作的方式。
M即model模型是指模型表示业务规则。在MVC的三个部件中,模型拥有最多的处理任务。被模型返回的数据是中立的,模型与数据格式无关,这样一个模型能为多个视图提供数据,由于应用于模型的代码只需写一次就可以被多个视图重用,所以减少了代码的重复性。
C即controller控制器是指控制器接受用户的输入并调用模型和视图去完成用户的需求,控制器本身不输出任何东西和做任何处理。它只是接收请求并决定调用哪个模型构件去处理请求,然后再确定用哪个视图来显示返回的数据。
简单来说:M是指业务模型,V是指用户界面,C则是控制器,使用MVC的目的是将M和V的实现代码分离,从而使同一个程序可以使用不同的表现形式。
路由源码:
业务模型:
var obj={}
var fs=require("fs")
var url=require("url")
var mime=require("mime")
var controller=require("./controller.js")
var router=function(req,res){
let pathname=url.parse(req.url).pathname
let type=mime.getType(pathname)
fs.readFile(router.basename+pathname,(err,data)=>{
if(!err){
res.setHeader("content-Type",type)
res.end(data)
}else{
if(obj[pathname]){
obj[pathname](req,res)
}else{
res.end("404 not found")
}
}
})
}
router.basename=__dirname+'/src'
router.stacte=function(path){
this.basename=path
}
router.get=function(path,callback){
obj[path]=callback
}
module.exports=router
控制器:
module.exports={
ajax1(req,res){
var obj={name:'ljy',age:22}
var str=JSON.stringify(obj)
res.setHeader("content-Type","text/json;charts-utf8")
res.end(str)
}
//在这里写业务函数向前端返回的数据
}
view界面
var http=require("http")
var router=require("./router.js")
var constroller=require("./controller.js")
http.createServer(router).listen(8081) //设置服务器,后面是设置监听的端口号
router.get("/ajax1",constroller.ajax1) //增加数据接口 , 需要再去配置控制器的业务函数
router.stacte(__dirname+'/src') //设置静态托管文件

边栏推荐
- 浅谈数据安全治理与隐私计算
- Understand the recommendation system in one article: Recall 06: Two-tower model - model structure, training method, the recall model is a late fusion feature, and the sorting model is an early fusion
- ExcelPatternTool: Excel table-database mutual import tool
- 第十四天&postman
- 亚马逊云科技 + 英特尔 + 中科创达为行业客户构建 AIoT 平台
- 力扣-二叉树的前序遍历、中序遍历、后序遍历
- 【Unity入门计划】2D游戏中遮挡问题的处理方法&伪透视
- Intel XDC 2022 Wonderful Review: Build an Open Ecosystem and Unleash the Potential of "Infrastructure"
- iNFTnews | 对体育行业和球迷来说,NFT可以带来什么?
- 如何看待自己的羞愧感
猜你喜欢

Hypervisor related knowledge points

【Endnote】Word插入自定义形式的Endnote文献格式

LPQ (local phase quantization) study notes

Three handshake and four wave in tcp
![[Unity Entry Plan] Handling of Occlusion Problems in 2D Games & Pseudo Perspective](/img/de/944b31c68cc5b9ffa6a585530e7be9.png)
[Unity Entry Plan] Handling of Occlusion Problems in 2D Games & Pseudo Perspective

Live preview | 30 minutes started quickly!Look at credible distributed AI chain oar architectural design

Understand the recommendation system in one article: Recall 06: Two-tower model - model structure, training method, the recall model is a late fusion feature, and the sorting model is an early fusion

Jincang database KingbaseES V8 GIS data migration solution (3. Data migration based on ArcGIS platform to KES)

How do programmers without objects spend the Chinese Valentine's Day

1349. 参加考试的最大学生数 状态压缩
随机推荐
LPQ(局部相位量化)学习笔记
How do programmers without objects spend the Chinese Valentine's Day
第09章 性能分析工具的使用【2.索引及调优篇】【MySQL高级】
Live preview | 30 minutes started quickly!Look at credible distributed AI chain oar architectural design
EBS利用虚拟列及hint 提示优化sql案例一则
“配置”是把双刃剑,带你了解各种配置方法
Using OpenVINO to implement the flying paddle version of the PGNet inference program
转:查尔斯·汉迪:你是谁,比你做什么更重要
直播回放含 PPT 下载|基于 Flink & DeepRec 构建 Online Deep Learning
SuperMap支持的国产环境汇总
网络安全与元宇宙:找出薄弱环节
记录谷歌gn编译时碰到的一个错误“I could not find a “.gn“ file ...”
Exercise: Selecting a Structure (1)
source program in assembly language
Log an error encountered when compiling google gn "I could not find a ".gn" file ..."
Understand the recommendation system in one article: Recall 06: Two-tower model - model structure, training method, the recall model is a late fusion feature, and the sorting model is an early fusion
汇编语言之源程序
《.NET物联网从零开始》系列
The difference between a process in user mode and kernel mode [exclusive analysis]
C language basics -- pointers