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/users/ will invoke the list action
HTTP GET to mysite/users/1 will invoke the single action
Currently it only works when I invoke (which is NOT what I want)
HTTP GET to mysite/users/list will invoke the list action
HTTP GET to mysite/users/single/1 will invoke the single action
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./users/ will invoke the list action
HTTP GET to mysite./users/1 will invoke the single action
Currently it only works when I invoke (which is NOT what I want)
HTTP GET to mysite./users/list will invoke the list action
HTTP GET to mysite./users/single/1 will invoke the single action
Share Improve this question edited Nov 2, 2015 at 20:37 Joe Hill 3333 silver badges12 bronze badges asked Sep 25, 2013 at 17:44 Max AlexanderMax Alexander 5,5816 gold badges41 silver badges54 bronze badges2 Answers
Reset to default 4Create 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);
}
};
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'
}
*/
};
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745544545a4632280.html
评论列表(0条)