Reputation: 68
I have Managed an API service base on Express JS. I have 2 or 3 clients that request my API. All the requests from the client are handled by single monolythic Apps. Currently, I handle that request with this code:
const express = require('express');
const webRoute = require('./src/routes/web/index')
const cmsRoute = require('./src/routes/cms/index');
app.use('/web', webRoute)
app.use('/cms', cmsRoute)
// This Code works just fine. The routes are defined by URL request
But I want the route request not from Url
, but requested by its Headers.
It looks like this appKey = 'for-key' appName='web'
curl -X GET \ http://localhost:3000/cms \ -H 'Authorization: Bearer asfsfafgdgfdgddafaggafafasgfghhjhkgflkjkxjvkjzvxzvz' \ -H 'Postman-Token: c36d6d5a-14b7-40bf-85e0-1bf255c815de' \ -H 'appKey: keyloggers' \ -H 'appName: web (i want by this header)' \ -H 'cache-control: no-cache'
Thx for all.
edit notes:
In my current code, to call an API I am using this:
https://localhost:3000/cms/user/profile or https://localhost:3000/web/user/profile
I want all requests to only use https://localhost:3000/user/profile
without adding a prefix web or cms
Upvotes: 0
Views: 1851
Reputation: 707258
Based on a comment, it appears you want to use a single URL form such as:
https://localhost:3000/user/profile
And, have it routed to the correct router based on the appName
custom header.
You can do that by just checking the custom header value and manually sending the request to the desired router.
const webRoute = require('./src/routes/web/index')
const cmsRoute = require('./src/routes/cms/index');
// custom middleware to select the desired router based on custom header
app.use((req, res, next) => {
const appName = req.get("appName");
if (appName === "web") {
webRoute(req, res, next);
} else if (appName === "cms") {
cmsRoute(req, res, next);
} else {
next();
}
});
Upvotes: 1
Reputation: 101
You can use a default route, then based on request headers, you can redirect to your route.
//consider this a default route. You can arrange any in your program
router.get('/', function (req, res) {
// switch on request header variable value
switch (req.get("appName")) {
case "web":
res.redirect('/web')
break;
case "cms":
res.redirect('/cms')
break;
}
})
Upvotes: 1