I have different version api developed using ExpressJs, I get version detail either through header or through query string like this example.com/users?version=1
and example.com/users?version=2
or I get in header.
I want to route my application api by query param I get through url
app.js
app.use('/', (req, res, next) => {
app.use(require('./v' req.query.version));
next();
});
I have two version in folder v1/index.js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World! v01')
});
module.exports = app;
and v2/index.js
as
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World! v02')
});
module.exports = app;
when I call api through url I only get response of version I call first
Like if I first call example.com/users?version=1
than I will get response as 'Hello World! v01'
,
after this if I call example.com/users?version=2
I get response as 'Hello World! v01'
If I call version=2 first time after starting script I will get 'Hello World! v02'
response every time.
I don't want to have application like example.com/v1
is their any way to get solve this version issue using query param or through header.
CodePudding user response:
Why you want to import dynamically may cause issues.
let say if I pass example.com/users?version=23424
// v1/index
const express = require("express");
const router = express.Router();
router.get("/", (req, res) => {
res.send("Hello World! v01");
});
module.exports = router;
// v2/index
const express = require("express");
const router = express.Router();
router.get("/", (req, res) => {
res.send("Hello World! v02");
});
module.exports = router;
// server
const express = require("express");
const app = express();
const v1 = require("./v1/index");
const v2 = require("./v2/index");
app.use("/", (req, res, next) => {
const { version } = req.query;
if (version !== "1" && version !== "2") {
return res.json({
message: "Not found",
});
}
const router = version === "1" ? v1 : v2;
router(req, res, next);
next();
});