从一个服务中,我发送一个请求到一个地址,例如http://gateway:3000/users,它使用http中间件库代理到http://webamqplib:5557/。如果我使用函数reverse-proxy-middlewareBuilder.ts,就能工作。
import { Request, Response, NextFunction } from 'express';
import { createProxyMiddleware, Filter, Options, RequestHandler } from 'http-proxy-middleware';
import { MiddlewareBuilder } from '@nestjs/core';
export function ReverseProxyMiddleware(req: Request, res: Response, next: NextFunction) {
const proxy = createProxyMiddleware(req.path, {
target: 'http://webamqplib:5557/',
changeOrigin: true,
})
proxy(req, res, next)
}创建的/users -> webamqplib:5557
模块-> users.module.ts
import { Request, Response, NextFunction } from 'express';
import { Injectable, NestMiddleware, Scope } from '@nestjs/common';
import { createProxyMiddleware, Filter, Options, RequestHandler } from 'http-proxy-middleware';
import configs from './config/config.json';
@Injectable()
export class ReverseProxyMiddleware implements NestMiddleware {
private proxy(path: Filter | Options, option?: Options): RequestHandler {
return createProxyMiddleware(path, option)
}
use(req: Request, res: Response, next: () => void) {
this.proxy(
req.path,
{
target: configs.users.target,
changeOrigin: true
}
)
next()
}使用类反向代理-中间件Builder.ts
import { Request, Response, NextFunction } from 'express';
import { Injectable, NestMiddleware } from '@nestjs/common';
import { createProxyMiddleware, Filter, Options, RequestHandler } from 'http-proxy-middleware';
import configs from './config/config.json';
@Injectable()
export class ReverseProxyMiddleware implements NestMiddleware {
private proxy(path: Filter | Options, option?: Options): RequestHandler {
return createProxyMiddleware(path, option)
}
use(req: Request, res: Response, next: () => void) {
this.proxy(
req.path,
{
target: configs.users.target,
changeOrigin: true
}
)
next()
}
}当请求http://gateway:3000/users时,控制台仍然显示HPM代理创建的: /users -> webamqplib:5557,就像函数一样,但是重定向不会像第一个示例那样发生在地址上。
在google翻译器的帮助下翻译:)
发布于 2022-10-26 16:29:15
在您的代码中,您为每个请求创建一个中间件,而不是将其连接一次,然后它将捕获请求。
在您的例子中,您必须在main.ts文件中这样做:
// main.ts
import { createProxyMiddleware } from 'http-proxy-middleware';
...
app.use("*", createProxyMiddleware({
target: 'http://webamqplib:5557',
changeOrigin: true,
}));对我来说是这样的。
https://stackoverflow.com/questions/70671232
复制相似问题