Reputation: 191
I created a proxy with the nestjs.
All requisitions pass normally. Except for POST requests.
Look at my code:
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)
Before it worked normally, after I put the proxy under NestJS only GET and OPTIONS requests work. Can you help me?
Upvotes: 4
Views: 23211
Reputation: 191
To solve the problem:
In main.ts right after my const app = await NestFactory.create(AppModule);
I have added the following lines:
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));
And I used the express-http-proxy
proxy library ie the requests that are not directed to my proxys NestJS can act.
Thank you
Upvotes: 5