NestJS代理创建问题:POST请求异常,附代码求助
Hey there! Let's figure out why your POST requests aren't forwarding correctly in your NestJS proxy. Based on the code snippet you shared and common pitfalls with NestJS proxy setups, here are the most likely issues and how to fix them:
1. You're Not Handling the Request Body
POST requests rely on a request body, but Node.js IncomingMessage is a stream—if you don't explicitly read and forward that stream, the target server will never receive the body. Your current code snippet doesn't show any logic to collect or pass the POST body, which is the #1 suspect here.
Fix: Collect and Forward the Request Body
Add code to gather the incoming request's body chunks, then write them to the proxy request:
@All('*') async proxy(@Req() req: IncomingMessage, @Res() res: http.ServerResponse) { // ... your existing target URL/options setup here ... // Step 1: Collect the incoming request body const bodyChunks: Buffer[] = []; await new Promise<void>((resolve, reject) => { req.on('data', (chunk) => bodyChunks.push(chunk)); req.on('end', resolve); req.on('error', reject); }); const requestBody = Buffer.concat(bodyChunks); // Step 2: Update headers to match the body length if (requestBody.length > 0) { options.headers['Content-Length'] = requestBody.length.toString(); } // Step 3: Send the proxy request with the body const proxyReq = http.request(options, (proxyRes) => { res.writeHead(proxyRes.statusCode!, proxyRes.headers); proxyRes.pipe(res); }); proxyReq.write(requestBody); proxyReq.end(); // ... error handling here ... }
2. NestJS's Default Body Parser is Consuming the Stream
NestJS uses body-parser under the hood to parse request bodies for routes. If your proxy controller doesn't disable this, the request stream gets consumed before your proxy code can read it—leaving an empty body to forward.
Fix: Disable Body Parsing for the Proxy Route
You can disable body parsing at the controller level or use raw parsing to preserve the stream:
import { UseInterceptors, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; import { Observable } from 'rxjs'; // Create a no-op interceptor to skip body parsing export class SkipBodyParsingInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): Observable<any> { const req = context.switchToHttp().getRequest(); req._parsedUrl = true; // Trick body-parser into skipping this request return next.handle(); } } // Apply it to your proxy controller @Controller('__api-proxy') @UseInterceptors(SkipBodyParsingInterceptor) export class ApiProxyController { // ... your proxy logic ... }
3. Incorrect or Missing Request Headers
POST requests often require specific headers like Content-Type or Content-Length to be valid. If these headers aren't copied correctly from the original request, the target server might reject the body.
Fix: Copy All Original Headers
Make sure you're passing through all headers from the incoming request to the proxy request:
const options = { // ... other options (hostname, path, method) ... headers: { ...req.headers }, // Copy all original headers };
Note: If your target server has strict header validation, you might need to adjust headers like Host to match the target domain.
4. Missing Error Logging
Without proper error handling, you won't know if the proxy request is failing silently (e.g., connection errors to the target server).
Fix: Add Error Listeners to the Proxy Request
const proxyReq = http.request(options, (proxyRes) => { // ... existing response handling ... }); proxyReq.on('error', (err) => { Log.error(`Proxy POST request failed: ${err.message}`, err); res.status(502).send('Proxy failed to connect to target server'); });
Add debug logs to print the incoming POST request's method, headers, and body size before forwarding—this will help you confirm if the request is being passed through correctly.
内容的提问来源于stack exchange,提问作者Hiago Souza

