我正在处理打字稿中的Node.js / express应用程序,该应用程序包含具有一些自定义业务逻辑来确定代理URL的代理路由:
import proxy from "http-proxy-middleware";
const controller = diContainer.get<IController>(TYPES.Controller);
const app = express();
app.use("/customProxy", controller.handleProxy());
@injectable()
export class Controller implements IController {
public handleProxy(): RequestHandler {
return proxy(
"**", // proxy all incoming routes
{
router: (req: Request) => {
// custom logic to translate route
return customRouteBasedOnIncomingRequest;
},
onProxyRes: (proxyRes: http.IncomingMessage, req: http.IncomingMessage, res: http.ServerResponse) => {
// custom logic to set outgoing response
res.setHeader("custom", "header")
},
}
});
}
}
我可以使用mock-express-request创建请求/响应对象,但是我不知道如何将其插入proxy
。
是否可以注入一个模拟来拦截发送代理请求的http客户端?理想情况下,我可以通过某种方式将此函数插入Controller
:
public mockedHttpServer(req: Request):Response
{
const res = new MockExrpessResponse();
if (req.url == "http://expected.url"){
res.write("success");
res.statuscode = 200;
}
else{
res.statuscode = 404;
}
return res;
}
试图钩住proxy.onProxyReq
并调用proxyReq.abort()
,然后尝试直接写入Response
,但这不会阻止实时请求发出。
还有另一种方法可以挂接到http堆栈并模拟网络io吗?
答案 0 :(得分:1)