【问题标题】:Create Proxy in NestJS在 NestJS 中创建代理
【发布时间】:2018-10-18 13:26:41
【问题描述】:

我用 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: 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 请求工作。你能帮帮我吗?

【问题讨论】:

    标签: node.js typescript nestjs


    【解决方案1】:

    解决问题:

    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 可以执行。

    谢谢

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-27
      • 1970-01-01
      • 2012-03-15
      相关资源
      最近更新 更多