恢复路由路径含义

restify route path meaning

我有下面的代码,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() 工作?

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

第一条路线是寻找来自“/path/*”的任何请求。只要领先的“/路径/”存在,它就会接受大多数值。 next() 用于重新定义以访问链中的下一个处理程序,这通常用于创建中间件但还有其他用途。

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

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

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

其他两条路径不言自明。他们选择一条路并采取相应的行动。您尝试使用 next() 做什么?

这让您了解 next 的用途...

// 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 吗?