I'm using the node-http-proxy library to create a forward proxy server. I eventually plan to use some middleware to modify the html code on the fly. This is how my proxy server code looks like
fastify v3.2.1
http-proxy v1.18.1
const fastify = require('fastify')();
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer();
fastify.post('/', (request, reply) => {
proxy.web(request.raw, reply.raw,
{
target: 'http://127.0.0.1:8084/a-node/demo',
ignorePath: true
},
(err) => {
if (err) {
reply.raw.statusCode = 500;
reply.raw.end('Error');
}
});
});
fastify.listen(9103);
I had this problem with a PUT request and was able to get it working with:
proxy.on('proxyReq', (proxyReq, req, res, options) => {
if (req.body) {
const bodyData = JSON.stringify(req.body);
proxyReq.setHeader('content-type', 'application/json');
proxyReq.setHeader('content-length', Buffer.byteLength(bodyData));
proxyReq.write(bodyData);
}
});
I feel like I'm doing something wrong, though, and this shouldn't be necessary.
Thanks @jaredjensen! That fixed it for me as well!
In my case I had to change it to
if (req.body && ['POST', 'PATCH', 'PUT'].includes(req.method)) {
const bodyData = JSON.stringify(req.body);
proxyReq.setHeader('content-type', 'application/json');
proxyReq.setHeader('content-length', Buffer.byteLength(bodyData));
proxyReq.write(bodyData);
}
because for get requests req.body was {} and the backend service was having issues with it
Does anyone have an idea on how to use this for e.g. multipart requests? In my case req.body is {} (maybe because I'm using nestjs and the middleware order messes up the request object?)
Update: this has been solved after making sure that the middleware using the proxy is the first one
let bufferStream = new Stream.PassThrough
/**
* Must using rawBody instead of qs.stringify because array value stringify error.
*/
bufferStream.end(Buffer.from(ctx.request.rawBody))
ctx.respond = false
proxy.web(ctx.req, ctx.res, { buffer: bufferStream }, next)
Hope this can help.
same issue - FYI I discovered it started to happen when I added koa-body middleware
Most helpful comment
I had this problem with a
PUTrequest and was able to get it working with:I feel like I'm doing something wrong, though, and this shouldn't be necessary.