Sails.js REST without action

2019-07-13 16:17发布

问题:

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

回答1:

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);
    }

};


回答2:

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'
}

*/
};