问题
I'm trying to create a custom route in Sails and according to their documentation, if I add the following in config/routes.js
:
'post /api/signin': 'AuthController.index',
The request would be dealt with by the index
action in the AuthController
but that doesn't seems to work at all. When I try the /api/login
in Postman, I get nothing back.
Please note that I've added restPrefix: '/api'
in my config/blueprints.js
. Please note I'm using Sails 0.12.x
What am I missing here?
回答1:
Since you are pointing to a controller with method index on it, you need to add it to your controllers and send a JSON response from there, (since you are using post). here is a simple example
config/routes.js
'post /api/signin': 'AuthController.index',
api/controllers/AuthController.js
module.exports = {
index: function(req, res) {
var id = req.param('id');
if(!id) {
return res.json(400, { error: 'invalid company name or token'});
}
/* validate login..*/
res.json(200, {data: "success"};
}
}
Update
Since you already have the above its probably caused by the blueprints you have.
Blueprint shortcut routes
Shortcut routes are activated by default in new Sails apps, and can be turned off by setting
sails.config.blueprints.shortcuts
tofalse
typically in /config/blueprints.js.Sails creates shortcut routes for any controller/model pair with the same identity. Note that the same action is executed for similar RESTful/shortcut routes. For example, the
POST /user
andGET /user/create
routes that Sails creates when it loadsapi/controllers/UserController.js
andapi/models/User.js
will respond by running the same code (even if you override the blueprint action)
with that being said from sails blueprint documentation, maybe turning off shortcuts and remove the prefix you've added.
possibly the shortcuts are looking elsewhere other than your controllers thus returning 404.
the prefix is being added to your blueprint connected route, hence you need
/api/api/signin
to access it?
Note
I am unable to replicate your issue on my computer as its working fine over here. but i have all blueprint settings turned off.
module.exports.blueprints = {
actions: false,
rest: false,
shortcuts: false,
// prefix: '',
pluralize: false,
populate: false,
autoWatch: false,
};
来源:https://stackoverflow.com/questions/39036419/how-to-create-a-custom-route-in-sails-js