gpt4 book ai didi

middleware - GET 以外的代理请求与 NestJS 和 http-proxy-middleware 挂起

转载 作者:行者123 更新时间:2023-12-03 13:57:22 29 4
gpt4 key购买 nike

示例代码可在 https://github.com/baumgarb/reverse-proxy-demo 上获得README.md 解释了如果您克隆存储库,如何重新产生问题。

我有一个 API 网关和一个返回 todos (TodosAPI) 的下游服务。客户端通过 API Gateway 访问下游服务。

API 网关正在利用 http-proxy-middleware包来代理请求。有两种实现,第二个不起作用:

1.main.ts中的全局中间件在路径/api/v1/... 上启动

这种方法工作得很好,它代理所有对下游服务的请求,无论是什么 http 方法(GET、PUT、...)。

import * as proxy from 'http-proxy-middleware';

app.use(
'/api/v1/todos-api',
proxy({
target: 'http://localhost:8090/api',
pathRewrite: {
'/api/v1/todos-api': ''
},
secure: false,
onProxyReq: (proxyReq, req, res) => {
console.log(
`[Global Functional Middlware]: Proxying ${req.method} request originally made to '${req.originalUrl}'...`
);
}
})
);

2. 在路径/api/v2/...启动的app模块中注册的NestMiddleware

这种方法适用于 GET 请求,但其他 http 方法(如 PUT)一直“挂起”,并且客户端从未收到任何响应。问题似乎是下游服务中的 Controller 从未被调用。
import * as proxy from 'http-proxy-middleware';

export class ReverseProxyMiddleware implements NestMiddleware {
private proxy = proxy({
target: 'http://localhost:8090/api',
pathRewrite: {
'/api/v2/todos-api': ''
},
secure: false,
onProxyReq: (proxyReq, req, res) => {
console.log(
`[NestMiddleware]: Proxying ${req.method} request originally made to '${req.originalUrl}'...`
);
}
});

use(req: Request, res: Response, next: () => void) {
this.proxy(req, res, next);
}
}

而这个中间件注册如下:
@Module({
imports: [],
controllers: [AppController],
providers: [AppService]
})
export class AppModule implements NestModule {
configure(consumer: import('@nestjs/common').MiddlewareConsumer) {
consumer
.apply(ReverseProxyMiddleware)
.forRoutes({ path: 'v2/todos-api', method: RequestMethod.ALL });
}
}
  • 运行curl -X PUT -H "Content-Type: application/json" -d "{\"id\": 1, \"userId\": 1, \"title\": \"delectus aut autem - v1\", \"completed\": true}" http://localhost:8080/api/v1/todos-api/1工作得很好
  • 运行curl -X PUT -H "Content-Type: application/json" -d "{\"id\": 1, \"userId\": 1, \"title\": \"delectus aut autem - v2\", \"completed\": true}" http://localhost:8080/api/v2/todos-api/1存在从不调用下游服务中的 Controller 的问题

  • NestMiddleware 正在代理请求(我可以看到一条日志行说 [NestMiddleware]: Proxying PUT request originally made to '/api/v2/todos-api/1'... )并且下游服务接收到请求(我可以从日志中看到)。但是下游服务不会调用 Controller / Action ,最终永远不会返回。

    有谁知道我在这里做错了什么?提前非常感谢!

    最佳答案

    我终于弄清楚了问题所在。它似乎与body parser有关。如果我更改 API 网关以关闭正文解析器,则请求将成功转发。

    所以解决方案是更换

    const app = await NestFactory.create(AppModule);


    const app = await NestFactory.create(AppModule, { bodyParser: false });

    我还创建了一个分支 issue-fixed在实现修复的 Git 存储库中。

    关于middleware - GET 以外的代理请求与 NestJS 和 http-proxy-middleware 挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58726968/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com