我在我的应用程序中使用sequelizejs,nodejs。我知道这会检查内部,但我想手动检查,就像if()条件一样。下面是一些url路径。
/user
/user/11d9b6130159 => user/:id
/user/11d9bdfg0159/sample => user/:id/sample
我想要的是,有中间件,必须检查当前的网址这些在应用程序路由喜欢
if(url.parse(req.url).path === "/user"){
//some action do
}
但是我没有通过剩余的urls。请给出解决方法。谢谢
发布于 2018-06-02 05:38:59
如果你真的想手动进行URL解析,那么方法可能是这样的:
编辑:根据您的评论,我修改了示例代码(超过3个级别)。您可以根据自己的需要轻松地扩展它。
const url = require('url');
const path = ctx.request.href;
const pathName = url.parse(path).pathname;
const pathNameParts = pathName.split('/'');
if (pathNameParts && pathNameParts[1] && pathNameParts[1] === 'user') {
if (pathNameParts[2]) {
const id = pathNameParts[2]; // :id is now defined
if (pathNameParts[3] && pathNameParts[3] === 'sample') {
if (pathNameParts[4]) {
const id2 = pathNameParts[4]; // :id2 is now defined
if (pathNameParts[5] && pathNameParts[5] === 'disable') {
// do some action for /user/:id/sample/:id2/disable
} else {
// do some action for /user/:id/sample/:id2
}
} else {
// do some action for /user/:id/sample
}
} else {
// do some action for /user/:id
}
} else {
// do some action for /user
}
}
所以,只有当你真的想自己做解析的时候,我才会这么做。否则,使用express路由器或koa路由器之类的东西。使用express路由器的情况如下所示:
app.use('/user/:id', function (req, res, next) {
console.log('ID:', req.params.id);
next();
});
https://stackoverflow.com/questions/50644806
复制相似问题