How to create a custom route in Sails JS

久未见 提交于 2020-02-25 04:50:26

问题


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


来源:https://stackoverflow.com/questions/39036419/how-to-create-a-custom-route-in-sails-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!