我有下面的代码,path
真的很混乱。改善的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()
工作?
答案 0 :(得分:0)
为了回答这个问题,我将带您完成代码并评论实际发生的事情。您已经了解这些路由是针对您的服务器的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'将条形图存储在req.params.id中。
app.get('/path/:name', function(req,res,next){
console.log('colon')
return next();
})
另外两条路径是不言自明的。他们采取相应的行动路径。你试图使用next()做什么?
答案 1 :(得分:0)
这可以让您了解下一步用于...
// 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?