/api/v1/resource for API versioning?URL path versioning explicitly includes the version in the URL, so the server can easily route requests to the correct version handler. This makes version management clear and straightforward.
X-API-Version to determine the API version, what happens if a client sends a request without this header?app.use((req, res, next) => {
const version = req.headers['x-api-version'] || '1';
if(version === '1') {
// handle v1
res.send('Response from API v1');
} else if(version === '2') {
// handle v2
res.send('Response from API v2');
} else {
res.status(400).send('Unsupported API version');
}
});The code uses a default value of '1' if the X-API-Version header is missing, so it responds with the v1 handler.
const express = require('express'); const app = express(); // Version 1 handler const v1Router = express.Router(); v1Router.get('/users', (req, res) => res.send('Users from v1')); // Version 2 handler const v2Router = express.Router(); v2Router.get('/users', (req, res) => res.send('Users from v2')); // Mount routers here // ??? app.listen(3000);
Mounting the routers on /api/v1 and /api/v2 correctly separates the versions in the URL path, allowing Express to route requests properly.
?version=2. What is the bug causing all requests to respond with 'Version 2 response' regardless of the query parameter?app.get('/api/users', (req, res) => { const version = req.query.version; if(version === '2') { res.send('Version 2 response'); } else { res.send('Version 1 response'); } });
The condition if(version = '2') assigns '2' to version instead of comparing it, so it always evaluates to true, causing the else block to never run.
/api/users with header X-API-Version: 2 given this Express.js code?const express = require('express'); const app = express(); app.use('/api', (req, res, next) => { req.apiVersion = req.headers['x-api-version'] || '1'; next(); }); app.get('/api/users', (req, res) => { switch(req.apiVersion) { case '1': res.send('Users from API v1'); break; case '2': res.send('Users from API v2'); break; default: res.status(400).send('Unsupported API version'); } }); app.listen(3000);
The middleware sets req.apiVersion from the header or defaults to '1'. The route reads this value and sends the matching response. Since the header is '2', it sends 'Users from API v2'.