【发布时间】:2019-11-05 10:37:55
【问题描述】:
我正在使用 typescript 开发一个 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 吗?
【问题讨论】:
标签: typescript express mocking http-proxy cucumberjs