Recently we faced issue to post the request via api server to another server to fix follow the
code as below:
In node app.js use following to proxy post request to different server:
const postProxy = createProxyMiddleware({
target: 'http://localhost:4000/', // Target server
changeOrigin: true, // Change the origin header to the target URL
pathRewrite: {
'^/api': '', // Remove /api from the path when forwarding
},
on: {
proxyReq: fixRequestBody
},
onProxyReq: (proxyReq, req, res) => {
// Forward request body for POST requests
if (req.body && Object.keys(req.body).length > 0) {
const bodyData = JSON.stringify(req.body);
proxyReq.setHeader('Content-Type', 'application/json');
proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
proxyReq.write(bodyData);
console.log(proxyReq);
}
},
logLevel: 'debug', // Enable detailed logs
});
// Proxy POST requests to /api/*
app.use(
'/api', postProxy
);
Cheers
Happy Coding !!
No comments:
Post a Comment
Thanks for your comment, will revert as soon as we read it.