我管理了一个基于 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 defined by url request
但我希望路线请求不是来自Url
而是由其标头请求,它看起来像这样appKey = 'for-key' appName='web'
curl -X GET \ http://localhost:3000/cms \ -H 'Authorization: Bearer asfsfafgdgfdgddafaggafagafasgfghhjhkgflkjkxjvkjzvxzvz' \ -H '邮递员-令牌:c36d6d5a-14b7-405ebf'keylogger'-H '邮递员-令牌:c36d6d5a-14b7-405ebf'keylogger'-hk36d6d5a-14b7-405ebf1'keylogger- H -H 'appName: web (我想要这个标题)' \ -H 'cache-control: no-cache'
谢谢大家
编辑笔记:
在我当前的代码中,要使用这个调用 apihttps://localhost:3000/cms/user/profile or https://localhost:3000/web/user/profile
我希望所有请求只使用https://localhost:3000/user/profile
而不添加前缀web或cms
根据评论,您似乎想要使用单个 URL 表单,例如:
https://localhost:3000/user/profile
并且,根据appName
自定义标头将其路由到正确的路由器。
您只需检查自定义标头值并手动将请求发送到所需的路由器即可。
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();
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句