在http-proxy-middleware
库中,文档指出您可以使用target
选项来指定您想要代理请求的位置。但是,它们还允许您使用 router
选项来指定一个函数,该函数将用于在运行时功能性地解析目标。
文档:https://www.npmjs.com/package/http-proxy-middleware
我正在使用 TypeScript,如果我查看代理的声明文件,我可以看到:
您可以在此处看到 router
和 target
都可为空。我的假设是,如果您使用其中一个,则可以省略另一个,但您始终至少需要 1 个。
但是,如果我像这样使用 router
属性:
app.use("/pipe", proxy({
changeOrigin: true,
router: (req: IIncomingMessageWithCookies) => {
return "https://www.google.com";
}
}));
并省略目标
,然后在运行时我收到此错误:
> node ./dist/app.js
C:\SkyKick\SkyKick.SEWR\src\node_modules\http-proxy-middleware\lib\config-factory.js:43
throw new Error(ERRORS.ERR_CONFIG_FACTORY_TARGET_MISSING)
^
Error: [HPM] Missing "target" option. Example: {target: "http://www.example.org"}
at Object.createConfig (C:\SkyKick\SkyKick.SEWR\src\node_modules\http-proxy-middleware\lib\config-factory.js:43:11)
at new HttpProxyMiddleware (C:\SkyKick\SkyKick.SEWR\src\node_modules\http-proxy-middleware\lib\index.js:17:30)
at module.exports (C:\SkyKick\SkyKick.SEWR\src\node_modules\http-proxy-middleware\index.js:4:10)
at Object.<anonymous> (C:\SkyKick\SkyKick.SEWR\src\dist\app.js:8:18)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
我意识到我可以将几乎任何东西放入 target
中,并且它会运行得很好,而我的 router
函数实际上定义了目标代理。这只是库的一个错误还是我误解了这两个选项的用途?
最佳答案
同时包含target
和router
属性。 router
属性用于针对特定请求重新定位option.target
。
import express = require('express');
import proxy = require('http-proxy-middleware');
const app = express();
app.use('/api', proxy({
target: 'http://www.github.com',
changeOrigin: true,
router: function (req: IncomingMessage) {
return 'http://www.stackoverflow.com'
}
}));
app.listen(3000);
target
属性在 Config
类型中是可选的,因为当我们 use the shorthand like this 时它允许为空。 :
app.use('/api', proxy('http://www.github.com',
{
changeOrigin: true,
router: function (req: IncomingMessage) {
return 'http://www.stackoverflow.com'
}
}
));
关于node.js - 如何使用 http-proxy-middleware 代理到许多不同的目标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56571972/