代码之家  ›  专栏  ›  技术社区  ›  agsonoo

恢复路线路径含义

  •  0
  • agsonoo  · 技术社区  · 10 年前

    我有下面的代码 path 真是令人困惑。restify的api指南没有解释太多。

    const restify = require('restify');
    
    const app = restify.createServer();
    
    app.get(/\/path\/.*/, function(req,res,next){
        console.log('regexp');
        return next(); // suppose to pass control to next handler, but nothing happended.
    })
    
    // it seems that '/path/:name' has the same meaning of /\/path\/.*/. Did I miss something?
    app.get('/path/:name', function(req,res,next){
        console.log('colon')
        return next();// still not pass control to next handler
    })
    
    // those two works as expected.
    app.get('/path/first', function(req,res,next){
        res.end('first');
    })
    
    app.get('/path/second', function(req,res,next){
        res.end('second');
    })
    
    app.listen(80, function () {
        console.log('Server is running');
    });
    

    那么有人能给我解释一下这条路的确切含义吗?我该怎么做 next() 工作

    2 回复  |  直到 10 年前
        1
  •  0
  •   hudsond7    10 年前

    为了回答这个问题,我将带您浏览代码并评论实际发生的情况。正如您已经理解的那样,这些路由是针对服务器的GET请求的。

    第一条路由是查找“/path/*”上的任何请求。只要存在前导“/path/”,它将接受大多数值。next()用于恢复以访问链中的下一个处理程序,这通常用于创建中间件,但也有其他用途。

    app.get(/\/path\/.*/, function(req,res,next){
        console.log('regexp');
        return next();
    })
    

    第二条路由与第一条路由相似,它接受“/path/*”上的任何内容。然而,这里的区别在于,第二个斜杠“/:id”之后的任何thign都将存储在req中。params作为变量。例如,点击“/path/12”会将12存储在req.params.id中。访问“/path/bar”会将bar存储在req.params.id中。

    app.get('/path/:name', function(req,res,next){
        console.log('colon')
        return next();
    })
    

    其他两条路径不言而喻。他们走一条路,并采取相应的行动。你想用next()做什么?

        2
  •  0
  •   danday74    10 年前

    这会让你知道下一步的用途。。。

    // log debug message on each request
    server.use(function request(req, res, next) {
      logger.debug(req.method, req.url);
      return next();
    });
    
    // validate jwt
    server.use(function request(req, res, next) {
      // validate web token here ... if invalid then respond 401 (unauthorised) else do a next ...
      return next();
    });
    
    app.get('/path/first', function(req,res,next){
        // return a response don't call next here
    })
    

    此外,在您的代码中,您使用的是res.end-不熟悉它(但它可能存在)-但您是否打算调用res.send??

    推荐文章