我使用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请求有效。你能救我吗?
答案 0 :(得分:0)
解决问题:
在我的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));
之后的main.ts中,我添加了以下几行:
express-http-proxy
我使用了runtimeType
代理库,即没有定向到我的代理NestJS的请求可以采取行动。
谢谢