在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";
}
}));省略target,然后在运行时得到以下错误:
> 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函数就是真正定义目标代理的东西。这只是库中的一个bug,还是我误解了这两个选项的用途?
发布于 2019-06-13 02:38:32
包括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类型中是可选的,因为当我们使用像这样用速记时允许它为空。
app.use('/api', proxy('http://www.github.com',
{
changeOrigin: true,
router: function (req: IncomingMessage) {
return 'http://www.stackoverflow.com'
}
}
));https://stackoverflow.com/questions/56571972
复制相似问题