[英]How to extract page name and authToken from url using express get route in nodejs?
[英]Nodejs - How to route by name in url with express and mongoose?
我有一个具有作者CRUD路由的Express 4服务器:
router.get('/authors', AuthorsController.index);
router.post('/authors', AuthorsController.store);
router.get('/authors/:name', AuthorsController.show);
router.put('/authors/:name', AuthorsController.update);
router.delete('/authors/:name', AuthorsController.remove);
我发现的大多数教程的路由都是/authors/:id
,然后执行Author.findById(req.params.id)
。 取而代之的是,我希望它是作者的名字,因此有一些可读的URL,例如: /authors/jk-rowling
。
我是否需要将连字符的字符串存储在Authors模型上,用express和Mongoosejs实现此目的的最佳方法是什么?
我的作者控制器当前看起来像这样:
const AuthorsController = {
async index(req, res){
const authors = await Author.find().populate('books');
res.send(authors);
}
};
(我正在将express-async-errors包用于带有express的async-await功能)
为带有Express和Mongoose的CRUD REST API建立具有人类可读URL的路由的最佳方法是什么?
您可以索引名称字段,并在视图中按名称查找(假设名称是“作者”的属性)
这不需要更改数据库模型。 您可以根据需要通过ID或名称进行搜索。
例如
router.get('/authors/:name', AuthorsController.show);
将有下面的看法
const AuthorsController = {
async show(req, res){
const authors = await Author.find({'name':req.params.name}).populate('books');
res.send(authors);
}
};
正如你在问题中提到,你将不得不产生像含代替空格或其他特殊字符连字符一个将被存储在模型和名称蛞蝓 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.