ExpressJS:添加前缀版本控制路由的最佳方式

时间:2017-10-17 05:49:02

标签: node.js express

我有:

let user = require('./model/user/user.route');
let companyType = require('./model/masterCollections/companyType/companyType.route');
let jobPosting = require('./model/jobPosting/jobPosting.route');
let login = require('./model/login/login.local');


module.exports = function(app) {
  app.use('/user', user);
  app.use('/companyType', companyType);
  app.use('/login', login.local);
  app.use('/jobs', jobPosting);
}

我可以为每个人添加手动前缀

  let prefix = '/api/v1'
  app.use(prefix + '/user', user);
  app.use(prefix + '/companyType', companyType);
  app.use(prefix + '/login', login.local);
  app.use(prefix + '/jobs', jobPosting);

但似乎对最佳做法不利。所以我的问题是添加版本控制的最佳方式是什么。

提前致谢。

1 个答案:

答案 0 :(得分:2)

建议按版本管理路径文件。

如果要求('文件夹')调用文件夹中的index.js。

我会告诉您我安排的页面。 http://camel.apache.org/bean-binding.html

<强> app.js

// ... skip ...

const apiv1 = require('./route/APIV1'); //./routes/APIV1/index.js
const apiv2 = require('./route/APIV2'); //./routes/APIV2/index.js

app.use('/APIV1', apiv1);
app.use('/APIV2', apiv2);

// ... skip ...
  • APIV1

<强> ./routes/APIV1/index.js

const express = require('express');
const router = express.Router();
const user = require('./user.js');
const jobs = require('./jobs.js');

router.use('/user', user);
router.use('/jobs', jobs);

module.exports = router;

<强> ./routes/APIV1/user.js

const express = require('express');
const router = express.Router();

router.get('/', function(req, res){
    res.end('/APIV1/user : get');
})


router.post('/', function(req, res){
    res.end('/APIV1/user : post');
})

module.exports = router;

<强> ./routes/APIV1/jobs.js

const express = require('express');
const router = express.Router();

router.get('/', function(req, res){
    res.end('/APIV1/jobs : get');
})


router.post('/', function(req, res){
    res.end('/APIV1/jobs : post');
})

module.exports = router;
  • APIV2

<强> ./routes/APIV2/index.js

const express = require('express');
const router = express.Router();
const user = require('./user.js');
const jobs = require('./jobs.js');

router.use('/user', user);
router.use('/jobs', jobs);

module.exports = router;

<强> ./routes/APIV2/user.js

const express = require('express');
const router = express.Router();

router.get('/', function(req, res){
    res.end('/APIV2/user : get');
})


router.post('/', function(req, res){
    res.end('/APIV2/user : post');
})

module.exports = router;

<强> ./routes/APIV2/jobs.js

const express = require('express');
const router = express.Router();

router.get('/', function(req, res){
    res.end('/APIV2/jobs : get');
})


router.post('/', function(req, res){
    res.end('/APIV2/jobs : post');
})

module.exports = router;

如果使用这种方式,您可以简单地管理您的API

快乐编码〜