Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic routes in SailsJs

I want to create a dynamic route. I created an API named users. And I need can access to /users/:nameofuser, like an auto created users/id.

How to get a username in this type of url, and execute a controller for search for it in the DB?

I try with this code in routes.js, but it doesn't work for me:

'users/:name': 'UserController.getUser',

'users/all/:name': 'UserController.getUser'

I always receive a 404 error with this text: No record found with the specified id.

like image 881
WIngenia Avatar asked Nov 26 '25 08:11

WIngenia


1 Answers

users/:id automatically routes to UserController.find. If this action is not present in your controller it uses the default blueprint action, which requires an ID parameter. To solve your problem you can simply override the find method:

find: function (req, res) {
    var name = req.param('id');
    User.findOne({name: name}).exec(function(err, user) {
        if (err) {return res.serverError(err);}
        return res.json(user);
    });
}

However if you still want to get users by ID you should create an extra route:

'users/:name': 'UserController.getUser',

and

getUser: function (req, res) {
    var name = req.param('name');
    User.findOne({name: name}).exec(function(err, user) {
        if (err) {return res.serverError(err);}
        return res.json(user);
    });
}
like image 83
UpCat Avatar answered Nov 27 '25 22:11

UpCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!