express 路由设置的问题
发布于 7 年前 作者 lpm0205 4939 次浏览 来自 问答

在一个express的项目中,有一个验证cookies的操作, 在登录成功后,之后进行的所有路由访问都进行了cookies的验证,能否在express中 ,通过在根路由中验证了cookies 从而之后的路由都不进行验证呢 类似情况如下 router.get(’/’, function(req, res, next) { // 在这里写验证cookies的方法 });

router.get(’/index’, function(req, res, next) { // 响应此路由时,先跳转回根目录的路由,进行cookies的验证, });

通过这个 可以减少代码冗余,也对一些路由中需要反复用到的操作进行精简

不知道社区的小伙伴有没有什么好的推荐

15 回复

@LIU9293 考虑过使用中间件,但是使用中间件的话,并不会减少代码冗余,代码量还是一致的,希望能有个精简代码量的方法

@lpm0205 那按照你写的也可以啊

router.get(’/’, function(req, res, next) {
   if(req.headers.cookies){
	  if(cookies can authorize){
	   next();
	  } else {
          ///cookies can not be authorized
	  }
   } else {
     /// no cookies
   }
});

@LIU9293 我的意思是在我响应下面的 /index路由时 能不能让/里的方法也调用,因为/index是基于/的路由 有点类似于调用子类时 自动使用父类的方法, 类似于这种功能 不知道在express中 是否有这种机制。

@lpm0205

'use strict'
const express = require('express');
const app = express();

app.all('*', (req, res, next) => {
  console.log('we are handling cookies');
  next();
})

app.get('/index', (req, res, next) => {
  res.send('hello world, we have handled cookies');
})

app.listen(8081);

console.log("server started on port " + 8081);

@LIU9293 Behaves just like middleware and can respond or call next to continue processing @lpm0205 和父子类继承不能类比的…

@lpm0205 express 本来就是为了做这种链式调用的啊,你说的这种功能就是express的目的。来一个更完善点的example:

http://localhost:8081/index http://localhost:8081/index?auth=true http://localhost:8081/?auth=true

'use strict'
const express = require('express');
const app = express();
const myRouter = express();

app.all('*', (req, res, next) => {
  if(req.query.auth === 'true'){
	next();
  } else {
	res.send('you do not have authorization!');
  }
});

app.use('/', myRouter)

// myRouter is your business logic, just focus on logic
myRouter.get('/index', (req, res, next) => {
  res.send('hello world, we have passed the authorization');
});

myRouter.get('*', (req, res, next) => {
  res.send('404');
});

app.listen(8081);

console.log("server started on port " + 8081);

@LIU9293 谢谢了 果然是大神 问题得到了解决~ 十分感谢

中间件。express的话:看app.use的api

@DevinXian 只是不知道该怎么表达,因此这么表达

@LIU9293 亲有用过 restful这种风格写的路由映射吗?

@lpm0205 https://github.com/LIU9293/musicafe 有兴趣的话可以看一下里面的server下面的内容,很简单的restful API

@LIU9293 感觉你server里的 api js就是express相关路由的设置方式,是不是express的路由就是遵照了restful的模式

@lpm0205 http://www.ruanyifeng.com/blog/2011/09/restful.html 现在最简单的理解就是所有东西都是API嘛,如果你都是res.render(),那就变成服务端模板了啊,反正我是觉得不用搞这么复杂,现在写网站不就这么几种嘛,服务端模板渲染,完全分离全是API,或者更超前一点的graphQL之类的

@LIU9293 是的,现在都是严格按照这种模式,请问你有用过 log4js winston buyan 这种日志文件吗,我现在想要实现日志的打印,通过代码的方式,方便他人操作。你有什么推荐的项目吗

回到顶部