How do you handle api version in a Node/Express app

后端 未结 3 1450
长情又很酷
长情又很酷 2021-01-30 05:16

I am pretty new to Node.js and I am facing the following issue.

My middleware started with the link api/v1/login and a bunch of endpoints. Then api/v1

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-30 06:05

    Frameworks like restify are better suited for api versioning, but if you are using express and need a lightweight module to version your routes, try this npm module https://www.npmjs.com/package/express-routes-versioning

    Module allows individual routes to be versioned separately. It supports basic semver versioning on the server to match multiple versions. (if needed). It is agnostic about specific versioning strategies and allows the application to set the version.

    Sample code

    var app = require('express')();
    var versionRoutes = require('express-routes-versioning')();
    app.listen(3000);
    app.use(function(req, res, next) {
        //req.version is used to determine the version
       req.version = req.headers['accept-version'];
       next();
    });
    app.get('/users', versionRoutes({
       "1.0.0": respondV1,
       "~2.2.1": respondV2
    }));
    
    // curl -s -H 'accept-version: 1.0.0' localhost:3000/users
    // version 1.0.0 or 1.0 or 1 !
    function respondV1(req, res, next) {
       res.status(200).send('ok v1');
    }
    
    //curl -s -H 'accept-version: 2.2.0' localhost:3000/users
    //Anything from 2.2.0 to 2.2.9
    function respondV2(req, res, next) {
       res.status(200).send('ok v2');
    }
    

提交回复
热议问题