在 NestJS 中创建代理

Create Proxy in NestJS

我用 nestjs 创建了一个代理。

所有申请都正常通过。 POST 个请求除外。

看看我的代码:

import { IncomingMessage } from 'http';
import { HttpUtils } from './../utils/http.utils';
import { Controller, Param, Req, Res, All } from '@nestjs/common';
import { Config } from './../system/config';
import { ServerResponse } from 'http';
import * as http from 'http';
import { CouchDB, Log } from 'system';
import { UsuarioModel } from 'model';

@Controller('__api-proxy')
export class ApiProxyController {

    @All('*')
    root(@Param() param, @Req() c_req: IncomingMessage, @Res() c_res: ServerResponse): any {

        // habilito o cors
        HttpUtils.enableCors(c_req, c_res);

        const urlDetail = HttpUtils.getUrlDetail(Config.getConfig().endpoints.webapi);

        // modifico para o hostname em que eu estou fazendo o proxy
        c_req.headers.host = urlDetail.hostname;

        // faço o proxy
        var proxy = http.request({
            hostname: urlDetail.hostname,
            port: urlDetail.port,
            method: c_req.method,
            headers: c_req.headers,
            path: '/' + param[0],
        }, (res) => {
            res.pause();
            res.headers.Server = `Sync Server ${Config.getConfig().package.version}`;

            if (Config.getConfig().endpoints.log) {
                Log.print('[ api ] [' + c_req.connection.remoteAddress + ']     : ' + c_req.method + ' ' + res.statusCode + ' ' + c_req.url);
            }

            c_res.writeHead(res.statusCode, res.headers);
            res.pipe(c_res, {end: true});
            res.resume();
        });

        c_req.pipe(proxy, {end: true});
    }
}

NodeJS error

Error: socket hang up
    at createHangUpError (_http_client.js:331:15)
    at Socket.socketOnEnd (_http_client.js:423:23)
    at emitNone (events.js:111:20)
    at Socket.emit (events.js:208:7)
    at endReadableNT (_stream_readable.js:1056:12)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickDomainCallback (internal/process/next_tick.js:218:9)

在它正常工作之前,在我将代理置于 NestJS 下后,只有 GET 和 OPTIONS 请求工作。你能帮帮我吗?

解决问题:

在我的 const app = await NestFactory.create(AppModule); 之后的 main.ts 中,我添加了以下行:

app.use('__bank-agency-gateway', proxy(config.endpoints.bankAgencyGateway));
app.use('__bank-account', proxy(config.endpoints.bankAcountCenter));
app.use('__bank-safebox', proxy(config.endpoints.bankSafebox));
app.use('__visa-proxy', proxy(config.endpoints.visaProxy));

并且我使用了 express-http-proxy 代理库,即未定向到我的代理的请求 NestJS 可以执行。

谢谢