express 中间件 的概念

4次阅读

共计 1808 个字符,预计需要花费 5 分钟才能阅读完成。

中间件
如果我的的 get、post 回调函数中,没有 next 参数,那么就匹配上第一个路由,就不会往下匹配了。如果想往下匹配的话,那么需要写 next()1app.get(“/”,function(req,res,next){2 console.log(“1”);3 next();4});56app.get(“/”,function(req,res){7 console.log(“2”);8});
下面两个路由,感觉没有关系:1app.get(“/:username/:id”,function(req,res){2 console.log(“1”);3 res.send(“ 用户信息 ” + req.params.username);4});56app.get(“/admin/login”,function(req,res){7 console.log(“2”);8 res.send(“ 管理员登录 ”);9}); 但是实际上冲突了,因为 admin 可以当做用户名 login 可以当做 id。
解决方法 1:交换位置。也就是说,express 中所有的路由(中间件)的顺序至关重要。匹配上第一个,就不会往下匹配了。具体的往上写,抽象的往下写。1app.get(“/admin/login”,function(req,res){2 console.log(“2”);3 res.send(“ 管理员登录 ”);4});56app.get(“/:username/:id”,function(req,res){7 console.log(“1”);8 res.send(“ 用户信息 ” + req.params.username);9});
解决方法 2:1app.get(“/:username/:id”,function(req,res,next){2 var username = req.params.username;3 // 检索数据库,如果 username 不存在,那么 next()4 if(检索数据库){5 console.log(“1”);6 res.send(“ 用户信息 ”);7 }else{8 next();9 }10});1112app.get(“/admin/login”,function(req,res){13 console.log(“2”);14 res.send(“ 管理员登录 ”);15});
路由 get、post 这些东西,就是中间件,中间件讲究顺序,匹配上第一个之后,就不会往后匹配了。next 函数才能够继续往后匹配。
app.use() 也是一个中间件。与 get、post 不同的是,他的网址不是精确匹配的。而是能够有小文件夹拓展的。比如网址:http://127.0.0.1:3000/admin/aa/bb/cc/dd1app.use(“/admin”,function(req,res){2 res.write(req.originalUrl + “n”); // /admin/aa/bb/cc/dd3 res.write(req.baseUrl + “n”); // /admin4 res.write(req.path + “n”); // /aa/bb/cc/dd5 res.end(“ 你好 ”);6});
如果写一个 /1// 当你不写路径的时候,实际上就相当于 ”/”,就是所有网址 2app.use(function(req,res,next){3 console.log(new Date());4 next();5});
app.use() 就给了我们增加一些特定功能的便利场所。实际上 app.use() 的东西,基本上都从第三方能得到。
● 大多数情况下,渲染内容用 res.render(),将会根据 views 中的模板文件进行渲染。如果不想使用 views 文件夹,想自己设置文件夹名字,那么 app.set(“views”,”aaaa”);● 如果想写一个快速测试页,当然可以使用 res.send()。这个函数将根据内容,自动帮我们设置了 Content-Type 头部和 200 状态码。send() 只能用一次,和 end 一样。和 end 不一样在哪里?能够自动设置 MIME 类型。● 如果想使用不同的状态码,可以:
res.status(404).send(‘Sorry, we cannot find that!’);
● 如果想使用不同的 Content-Type,可以:
res.set(‘Content-Type’, ‘text/html’);

正文完
 0