How do I namespace my api in sails.js like so /api/v1?

守給你的承諾、 提交于 2019-12-03 14:31:00
Benedikt

There is three ways of doing this.

1st: blueprints

http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.blueprints.html how to create a global route prefix in sails?

prefix: '/api'

or restPrefix: '/api'

how to create a global route prefix in sails?

2nd: in each controller adding

_config: { prefix: '/api/v2' }

3rd: configure it in the routes

http://sailsjs.org/#!/documentation/concepts/Routes

'/api/v2/': 'FooController',

Whereas other frameworks allow you to nest a block or closure, you can't do so in Sails. My approach is to use a variable that holds the prefix and apply it (after evaluating the string) to each route object key as such:

const prefix = '/my/api/v2';

module.exports = {
  [`GET ${prefix}/where/ever/you/want`]: { ... },

  [`POST ${prefix}/some/where/nice`]: { ... },
}

The above uses string interpolation with ES6. If you do not have that, just use string concatenation: ['GET ' + prefix + '/where/ever']: { ... }.

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