如何在羽毛js中生成多级路径参数,如下所示:
api.com/category/catergoryId/subCatergory/subCatergoryId
发布于 2017-11-01 02:10:44
以下内容摘自此羽毛FAQ条目
通常情况下,我们会发现它们实际上并不是必需的,最好是让你的路线尽可能的平坦。例如,像
users/:userId/posts这样的东西--尽管对人类来说读起来不错--实际上并不像已经被现成的羽毛支持的同等的/posts?userId=<userid>那样容易解析和处理。此外,这也将更好地工作时,使用羽毛通过websocket连接,根本没有一个路线的概念。 但是,仍然可以通过在嵌套路由上注册现有服务并将路由参数映射到如下所示的查询参数来创建服务的嵌套路由:
app.use('/posts', postService);
app.use('/users', userService);
// re-export the posts service on the /users/:userId/posts route
app.use('/users/:userId/posts', app.service('posts'));
// A hook that updates `data` with the route parameter
function mapUserIdToData(hook) {
if(hook.data && hook.params.userId) {
hook.data.userId = hook.params.userId;
}
}
// For the new route, map the `:userId` route parameter to the query in a hook
app.service('users/:userId/posts').hooks({
before: {
find(hook) {
hook.params.query.userId = hook.params.userId;
},
create: mapUserIdToData,
update: mapUserIdToData,
patch: mapUserIdToData
}
})现在转到
/users/123/posts,将调用postService.find({ query: { userId: 123 } })并返回该用户的所有帖子。
https://stackoverflow.com/questions/47017301
复制相似问题