当前位置: 首页 > 后端技术 > Node.js

express中间件的概念

时间:2023-04-03 15:47:08 Node.js

中间件如果我的get和post回调函数中没有next参数,那么就会匹配第一个路由,不会再进行匹配。如果要往下匹配,需要写next()1app.get("/",function(req,res,next){2console.log("1");3next();4});56app.get("/",function(req,res){7console.log("2");8});以下两条路由感觉无关紧要:1app.get("/:username/:id",function(req,res){2console.log("1");3res.send("UserInformation"+req.params.username);4});56app.get("/admin/login",function(req,res){7console.log("2");8res.send("管理员登录");9});但实际上是有冲突的,因为admin可以作为用户名,login可以作为id。解决方案1:交换位置。换句话说,express中所有路由(中间件)的顺序很关键。如果它匹配第一个,它就不会匹配下一个。具体的写上去,抽象的写下来。1app.get("/admin/login",function(req,res){2console.log("2");3res.send("管理员登录");4});56app.get("/:username/:id",function(req,res){7console.log("1");8res.send("用户信息"+req.params.username);9});方案二:1app.get("/:username/:id",function(req,res,next){2varusername=req.params.username;3//检索数据库,如果username不存在,则next()4if(检索数据库){5console.log("1");6res.send("用户信息");7}else{8next();9}10});1112app.get("/admin/login",function(req,res){13console.log("2");14res.send("管理员登录");15});路由get、post等东西都是中间件,中间件讲究顺序,匹配到第一个之后,就不会再有后面的匹配了。next函数可以继续向后匹配。app.use()也是一个中间件。与get和post不同,他的URL不是完全匹配的。相反,它可以用小文件夹扩展。例如URL:http://127.0.0.1:3000/admin/aa/bb/cc/dd1app.use("/admin",function(req,res){2res.write(req.originalUrl+"n");///admin/aa/bb/cc/dd3res.write(req.baseUrl+"n");///admin4res.write(req.path+"n");///aa/bb/cc/dd5res.end("你好");6});如果不写路径的时候写一个/1//,其实就相当于“/”,就是所有的url2app.use(function(req,res,next){3console.log(newDate());4next();5});app.use()为我们提供了一个方便的地方来添加一些特定的功能。其实关于app.use()的一切基本上都可以从第三方获取。●大多数情况下,res.render()用于渲染内容,内容会根据视图中的模板文件进行渲染。如果你不想使用views文件夹,想自己设置文件夹名称,那么app.set("views","aaaa");●如果你想快速写一个测试页,当然可以使用res.send()。这个函数会根据内容自动为我们设置Content-Type头和200状态码。send()只能使用一次,与end相同。和end有什么区别?能够自动设置MIME类型。●如果你想使用不同的状态码,你可以:res.status(404).send('抱歉,我们找不到那个!');●如果你想使用不同的Content-Type,你可以:res.set('Content-Type','text/html');