How to query a request at Nodejs Proxy Server? - node.js

I have a Nodejs Proxy server like this:
`var http = require('http'),
httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({});
proxy.on('proxyReq', function(proxyReq, req, res, options) {
proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
});
var server = http.createServer(function(req, res) {
console.log(req.body);
proxy.web(req, res, {
target: 'http://localhost:3000'
});
});
console.log("listening on port 9000")
server.listen(9000);`
What i want is get the req.body at the proxy server when i post a request to the Origin server, go through the proxy server.
I used "console.log(req.body);" at both proxy server and the origin server. I get the body object {"id": "user003"} at origin server, but undefined at the proxy server.
So how can i get the req.body at proxy server?

I suspect the problem here is that you don't have a body parser on your proxy server, but do have one on your origin.
req.body itself isn't set by node. Instead, you have to handle events emitted by the req stream:
let body = '';
req.on('data', (data) => {
// data is a buffer so need toString()
body += data.toString();
});
req.on('end', () => {
// at this point you'll have the full body
console.log(body);
});
You can make this easier with a body parser (e.g https://www.npmjs.com/package/body-parser) but since you're running a proxy server, you probably don't want to parse the entire req stream before forwarding onto your origin. So I'd maybe stick with handling the events.

Related

Nodejs: how to clone or duplicate an incoming soap http request?

My Node.js server receives http soap requests. I would like to clone/duplicate each requests in order to send one to server A and the other to server B. How can I do that? Thanks
var proxy = httpProxy.createProxyServer({changeOrigin: true});
app.all('/', (req, res) =>{
// Duplicate or clone request
// ..... and send it to server B
// Forward original request to Server A
proxy.web(req, res, { target: url_serverA }, function(e) {})
});

No headers in proxied request with Express

My express server has to proxy requests to another server listening on a unix socket file.
app.all('*', (req, res) => {
let opts = {
socketPath: 'file.sock',
path: req.url,
method: req.method,
headers: req.headers
};
const proxyReq = http.request(opts, (proxyRes) => {
proxyRes.pipe(res, {
end: true
});
});
req.pipe(proxyReq, { end: true });
});
The problem is that the response headers are not being passed on from the proxied server to the Express response. The client gets the Express server headers instead.
My questions:
How do I correctly pipe all of proxyRes into res?
Is there a way I can avoid having the proxied server response parsed and pipe the raw socket data back to the client? The same applies to the request. I'd like making the proxying as transparent as possible while keeping Express as the top level server.

Forward http proxy using node http proxy

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
var httpProxy = require('http-proxy')
httpProxy.createServer(function(req, res, proxy) {
var urlObj = url.parse(req.url);
console.log("actually proxying requests")
req.headers.host = urlObj.host;
req.url = urlObj.path;
proxy.proxyRequest(req, res, {
host : urlObj.host,
port : 80,
enable : { xforward: true }
});
}).listen(9000, function () {
console.log("Waiting for requests...");
});
Now I modify chrome's proxy setting, and enable web proxy server address as localhost:9000
However every time I visit a normal http website, my server crashes saying "Error: Must provide a proper URL as target"
I am new at nodejs, and I don't entirely understand what I'm doing wrong here?
To use a dynamic target, you should create a regular HTTP server that uses a proxy instance for which you can set the target dynamically (based on the incoming request).
A bare bones forwarding proxy:
const http = require('http');
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({});
http.createServer(function(req, res) {
proxy.web(req, res, { target: req.url });
}).listen(9000, () => {
console.log("Waiting for requests...");
});

Node js Reverse Proxy PUT/POST Requests w/ Couchbase Sync Gateway

I'm trying to build a reverse proxy in front of a Couchbase SyncGateway. Before sending requests to the sync gateway, I'd like to send them to an authentication server for authentication, then if all is good, send the request on (unmodified from original) to the sync gateway. The database is not staying up to date with the client modifications and I believe this is because I am not successfully proxying PUT/POST requests. Here is the code I have:
var http = require('http');
var httpProxy = require('http-proxy');
var apiProxy = httpProxy.createProxyServer();
var request = require('request').defaults({json: true});
var authServer = 'http://authserverdns:5000';
var syncGateway = 'http://syncgatewaydns:4984';
http.createServer(function (req, res) {
if (req.method == 'POST' || req.method == 'PUT') {
req.body = '';
req.addListener('data', function(chunk) {
req.body += chunk;
});
req.addListener('end', function() {
processRequest(req, res);
});
} else {
processRequest(req, res);
}
}).listen(8080);
function processRequest(req, res) {
request(authServer, function(error, response, body) {
if (body.authenticated) {
console.log('authenticated !!!');
apiProxy.web(this.req, this.res, {target: this.sg});
} else {
console.log('request denied !!!');
}
}.bind({req: req, res: res, sg: syncGateway}));
}
At first I was using an express server and having same issue. As I looked into the problem, it looks like maybe there is an issue with Express and proxying PUT/POST requests. So, I attempted to use some examples out there and this is what I've ended up with, but still not working. Any ideas as to where I'm going wrong here? Authenticated prints, so I know I'm getting to the point of proxying. And the sync gateway seems to be fine with the GET requests.
Thanks
ugh. I wasn't adding the rest of the URL to the forwarding address for the Sync Gateway. The post here helped.

NodeJS HTTP proxy - Add a header and update the request URL

I am using this module to do the following:
Parse the req URL
Add a new header to the request using the token from the URL
Update the actual request URL (remove the token from the URL)
I am trying to do that with the following code:
function initializeServer(){
var server = app.listen(5050, function () {
var host = server.address().address
var port = server.address().port
logger.info('NodeJS Server listening at http://%s:%s', host, port)
});
}
proxy.on('proxyReq', function(proxyReq, req, res, options) {
console.log("intercepting ... ")
proxyReq.setHeader('x-replica', '123');
req.url = '/newurl';
});
function initializeController(){
app.get('/myapp*', function (req, res) {
proxy.web(req, res, { target: 'http://127.0.0.1:8081' });
});
}
where 8081 is my test server and proxy server runs at 5050.
Now, the header setting works but the setting the URL does not. How to achieve this with node HTTP proxy ?
In the proxy.on('proxyReq',...) handler req is the (original) incoming request, while proxyReq is the request that will be issued to the target server. You need to set the proxyReq.path field.

Resources