Home > Mobile >  Express JS : How to manage routing by headers request?
Express JS : How to manage routing by headers request?

Time:09-25

I was Managed an API service base on Express JS. i have 2 or 3 client that request to my API. All the request from client are handled by single monolythic Apps, currently i was 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 defined by url request

but i want the routes request not from Url but requested by its Headers its look 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 using this https://localhost:3000/cms/user/profile or https://localhost:3000/web/user/profile i want All request only use https://localhost:3000/user/profile without add a prefix web or cms

CodePudding user response:

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;
}
})

CodePudding user response:

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();
    }
});
  • Related