Sails.js REST without action

2019-07-13 16:39发布

I'm trying to create a REST API in Sails.js 0.9x

I have a controller like the following:

UsersController = {
    list: function(req, res){
            var users [{username: "max"}, {username:'alison'}];
       res.send(users);

     },
    single: function(req, res){
            var user = {username: 'max'};
            res.send(user);
         }

};

How would I be able to access the URLs using an HTTP Method and the Route without specifying the action name?

For example

HTTP GET to mysite.com/users/ will invoke the list action

HTTP GET to mysite.com/users/1 will invoke the single action

Currently it only works when I invoke (which is NOT what I want)

HTTP GET to mysite.com/users/list will invoke the list action

HTTP GET to mysite.com/users/single/1 will invoke the single action

2条回答
姐就是有狂的资本
2楼-- · 2019-07-13 17:02

Create an index action that redirects to other actions.

UsersController = {
    index: function(req, res) {
        if(req.param('idOrWhateverYouHaveDefined')) {
           this.single(req, res);
        }else {
           this.list(req, res);
        }
    },
    list: function (req, res) {
        var users[{
            username: "max"
        }, {
            username: 'alison'
        }];
        res.send(users);

    },
    single: function (req, res) {
        var user = {
            username: 'max'
        };
        res.send(user);
    }

};
查看更多
别忘想泡老子
3楼-- · 2019-07-13 17:05

I think this might be a better solution

Create/Edit the config/route.js and explicitly define the routes and their associated actions Link from the documentation

module.exports.routes = {
// Standard RESTful routing

// If no id is given, an array of all users will be returned
'get /user/:id?': {
    controller    : 'user',
    action        : 'find'
}
'post /user': {
    controller    : 'user',
    action        : 'create'
}
'put /user/:id': {
    controller    : 'user',
    action        : 'update'
}
'delete /user/:id': {
    controller    : 'user',
    action        : 'destroy'
},

// Override the default index action (find) by declaring an "index" method in your controller
'get /user': {
    controller    : 'user',
    action        : 'index'
}

*/
};
查看更多
登录 后发表回答