简体   繁体   English

节点快递订单路线

[英]node express order routes

I have my routes setup like that: 我有这样的路线设置:

app.use('/', index);
app.use('/auth', auth);
app.use(RequestHandlers.Authorize);    
app.post('/users', users);    
// catch 404 and forward to error handler
app.use(RequestHandlers.NotFound);

My handlers: 我的管理员:

export function Authorize(req: Request, res: Response, next: Function) {

    // check header or url parameters or post parameters for token
    var token = req.body.token || req.query.token || req.headers['x-access-token'];
    //token logic
  };

export function NotFound(req: Request, res: Response, next: Function) {
    var err: any = new Error('Not Found');
    err.status = 404;
    next(err);
  }

So I have no problems to handle any defined routes but when I am accessing any not existed routes the RequestHandlers.Authorize always getting executed first. 因此,处理任何已定义的路由都没有问题,但是当我访问任何不存在的路由时,总是首先执行RequestHandlers.Authorize But if the route is not existed I want to fire app.use(RequestHandlers.NotFound); 但是,如果路由不存在,我想触发app.use(RequestHandlers.NotFound);

How can I do that? 我怎样才能做到这一点? What is the best approach without putting much custom logic on the routes? 在路由上不添加太多自定义逻辑的最佳方法是什么? May be there is the way to check if route is defined? 也许有办法检查是否定义了路线?

When you do app.use(fn) you're saying "use this middleware function for every request". 当您执行app.use(fn)您的意思是“对每个请求使用此中间件功能”。

Seeing as you only want the authorize function to run on specific routes, you should add it to only those routes, using the following method: 鉴于您只希望在特定路由上运行authorize功能,因此应使用以下方法将其仅添加到那些路由:

app.get('/', middleware, fn)

…so for your specific example: …因此针对您的特定示例:

app.get('/', RequestHandlers.Authorize, index)
app.get('/users', RequestHandlers.Authorize, users)

The middleware argument when creating a route can be a function (req, res, next) or it can be an array of functions. 创建路由时的middleware参数可以是一个function (req, res, next) ,也可以是一个函数数组。

More info here: http://expressjs.com/en/guide/routing.html#route-handlers 此处提供更多信息: http : //expressjs.com/en/guide/routing.html#route-handlers

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM