Vishwajeet Vatharkar
Vishwajeet Vatharkar

Reputation: 1196

How to set a base path for SailsJS APIs?

The sailsJS routes by default are mapped to / base path.

For e.g.'get /user/getUser': 'User.getUser', is mapped to /user/getUser/

Now, I want to set a base path for API endpoints, which should be dynamic.

For e.g. 'get /user/getUser': 'User.getUser' should map to /api/user/getUser/ , while the /api/ string should be dynamic.

I am unable to set this key name dynamically, like get ${apiBase}/user/getUser.

Is there any way to set the base path for APIs in SailsJS (v1.0.2)

Upvotes: 0

Views: 267

Answers (1)

arbuthnott
arbuthnott

Reputation: 3819

I think you can do this by editing your config/blueprints.js config file. Add:

module.exports = {
    // ...
    prefix: '/api',
};

If you otherwise have blueprints turned on, then this will map all controller actions. A User.getUser controller action is now reachable at {yoururl}/api/user/getUser without any further configuration of routes.

Of course, if you override any of these in your routes.js file, then the prefix /api is not automatically used.

That said, I can't see any impediment to getting and using that in your routes.js file:

var prefix = require('./blueprints.js').blueprints.prefix || '/';
module.exports.routes = {
    // ...
    'GET ' + prefix + '/user/getUser/:id': 'UserController.getUser',
};

docs on blueprint config are here: https://sailsjs.com/documentation/reference/configuration/sails-config-blueprints

Upvotes: 1

Related Questions