WagnerMatosUK
WagnerMatosUK

Reputation: 4429

How to create a custom route in Sails JS

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?

Upvotes: 1

Views: 1857

Answers (1)

Bamieh
Bamieh

Reputation: 10906

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 to false 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 and GET /user/create routes that Sails creates when it loads api/controllers/UserController.js and api/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.

  1. possibly the shortcuts are looking elsewhere other than your controllers thus returning 404.

  2. 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,
};

Upvotes: 2

Related Questions