node.js - 如何使用 http-proxy-middleware 代理到许多不同的目标?

标签 node.js typescript proxy http-proxy http-proxy-middleware

http-proxy-middleware库中,文档指出您可以使用target选项来指定您想要代理请求的位置。但是,它们还允许您使用 router 选项来指定一个函数,该函数将用于在运行时功能性地解析目标。

文档:https://www.npmjs.com/package/http-proxy-middleware

我正在使用 TypeScript,如果我查看代理的声明文件,我可以看到:

proxy

您可以在此处看到 routertarget 都可为空。我的假设是,如果您使用其中一个,则可以省略另一个,但您始终至少需要 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 函数实际上定义了目标代理。这只是库的一个错误还是我误解了这两个选项的用途?

最佳答案

同时包含targetrouter 属性。 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/

相关文章:

javascript - ionic react ,滚动到特定列表项

proxy - 如何从 Twisted 中的 XML-RPC 回调发送 XML-RPC 请求

angularjs - MongoDB - InsertOne() 获取 InsertID

node.js - 在 node.js 中直接使用 PhantomJS 的问题

javascript - Typescript 无法识别 VS 2015 中的 Javascript

typescript - 为什么在这里添加构造函数会破坏 Angular 2?

java - 通过另一台服务器向另一台服务器发送请求,从最终服务器获取响应

linux - tinyproxy:如何在 Ubuntu 上手动安装最新版本 1.11.0?

node.js - 如何在 Angular 应用程序中提供 txt 文件

node.js - Keystone 无法隐藏 x-powered-by