Express JS:如何通过 headers 请求管理路由?

Express JS : How to manage routing by headers request?

我管理了一个基于 Express JS 的 API 服务。我有 2 或 3 个客户请求我的 API。来自客户端的所有请求都由 单一单体应用程序 处理。目前,我使用以下代码处理该请求:

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

但我想要的路由请求不是来自 Url,而是它的 Headers 请求的。 看起来像这样 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'

谢谢大家。

编辑笔记:

在我当前的代码中,调用 API 我正在使用这个:

https://localhost:3000/cms/user/profile or https://localhost:3000/web/user/profile 我希望所有请求只使用 https://localhost:3000/user/profile 而不添加前缀 webcms

您可以使用默认路由,然后根据请求 headers,您可以重定向到您的路由。

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

根据评论,您似乎想使用单个 URL 表单,例如:

https://localhost:3000/user/profile

并且,根据 appName 自定义 header 将其路由到正确的路由器。

您只需检查自定义 header 值并手动将请求发送到所需路由器即可。

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