Check if request is in state of re-direct - node.js

There is a way with express check if the request is in status redirect (302) ,I use the( req,res ) I use the following ?
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');
});
proxy.on('proxyRes', function (proxyRes, req, res) {
console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, true, 2));
});
https://github.com/nodejitsu/node-http-proxy

Maybe I don't understand the question, but you can easily do the following:
proxy.on('proxyRes', function(proxyRes, req, res) {
if (proxyRes.statusCode === 301 || proxyRes.statusCode === 302) {
proxyRes.headers['location'] = fixUrl(proxyRes.headers['location']);
}
});
Where fixUrl() does any necessary transform on the location response header.

You can listen for proxyRes event and check its status code (status code for redirection is 30x). ProxyRes is a raw response from your target, so you should be able to catch and modify the response headers before the proxy send this response to the client.
Alternatively, you can also set the proxy options that handle 30x redirects. Either setting the autoRewrite to true or explicitly state the location in the hostRewrite and protocolRewrite should do the trick. https://github.com/nodejitsu/node-http-proxy#options

Related

How to duplicate and forward a request with koa router

For several reasons, I have a server that has to forward requests to another server. The response should be the response of the final server. I also need to add an extra header onto the request but remove this header again from the response before returning. As such, redirect isn't going to cut it.
I'm currently doing it manually copying the headers & body as required but I would like to know if there's a simple generic way to do it?
A proxy would work for this. Assuming #koa/router or something simliar and the http-proxy module (there are also wrapper modules for Koa that may work:
const proxy = httpProxy.createProxyServer({
target: 'https://some-other-server.com',
// other options, see https://www.npmjs.com/package/http-proxy
})
proxy.on('proxyReq', (proxyReq, req, res, options) => {
proxyReq.setHeader('x-foo', 'bar')
})
proxy.on('proxyRes', (proxyRes, req, res) => {
proxyRes.removeHeader('x-foo')
})
router.get('/foo', async (ctx) => {
// ctx.req and ctx.res are the Node req and res, not Koa objects
proxy.web(ctx.req, ctx.res, {
// other options, see docs
})
})
You could also lift the proxy out of a route if you happen to be starting your Koa server with http.createServer rather than app.listen:
// where app = new Koa()
const handler = app.callback()
http.createServer((req, res) => {
if (req.url === '/foo') {
return proxy.web(req, res, options)
}
return handler(req, res)
})

Pass value from http.request or superagent to http.createServer NodeJs

I am not sure what the issue is but I think I have to make this async or promise based (idk how). I simply want to pass the callback to http server on res.end.
Can some one help please?
HTTP Request or SuperAgent passes the value to the function below. How to send this to http.createserver ?
function receiveCallback(link) {
console.log(link);
//this works fine, echos the LINK we want to 302 to
}
How to pass link to http server?
http.createServer(function (req, res) {
res.writeHead(302, {'Location': link});
res.end();
}).listen('8080');
Ex. User opens domain.com/test?somevar
somevar is sent to superagent which then produces a link
How to 302 the user to the link
If your superagent is making its own request every time the server gets a request, it would look something like this:
const http = require('http');
const url = require('url');
const request = require('superagent');
http.createServer((req, res) => {
const queryParams = url.parse(req.url, true).query;
request
.get('/get/my/link')
.send({ somevar: queryParams.somevar })
.end((err, response) => {
if (err)
throw err;
const link = response.body.link;
res.writeHead(302, { 'Location': link });
res.end();
});
}).listen('8080');

How to res.send to a new URL in Node.js/Express?

Given a GET request to URL X, how should you define res.send such that it provides a response to a completely separate URL Y?
i.e.
app.get('/', function (req, res) {
res.send to a new URL external of the app ('Success')
});
Thanks and apologies in advance for ignorance on the topic!
You want to redirect the request by setting the status code and providing a location header. 302 indicates a temporary redirect, 301 is a permanent redirect.
app.get('/', function (req, res) {
res.statusCode = 302;
res.setHeader("Location", "http://www.url.com/page");
res.end();
});
You can only send response to the request source, which is the client. There is no such thing as sending response to another "external-url" (or another server).
However, you CAN make a request to another server, wait for it's response, and respond to our client.
app.get('/', (req, res) => {
var requestOptions = {
hostname: 'serverB.com', // url or ip address
port: 8080, // default to 80 if not provided
path: '/take-request',
method: 'POST' // HTTP Method
};
var externalRequest = http.request(requestOptions, (externalResponse) => {
// ServerB done responding
externalResponse.on('end', () => {
// Response to client
res.end('data was send to serverB');
});
});
// Free to send anthing to serverB
externalRequest.write(req.data);
externalRequest.end();
});

NodeJS - Reverse Proxy with Route Changing

I'm currently using NodeJS/Express as a simple domain router running on my VPS on port 80. My routes.coffee looks something like this:
request = require("request")
module.exports = (app) ->
#404, 503, error
app.get "/404", (req, res, next) ->
res.send "404. Sowway. :("
app.get "/error", (req, res, next) ->
res.send "STOP SENDING ERRORS! It ain't cool, yo."
#Domain Redirects
app.all '/*', (req, res, next) ->
hostname = req.headers.host.split(":")[0]
#Website1.com
if hostname == 'website1.com'
res.status 301
res.redirect 'http://facebook.com/website1'
#Example2.com
else if hostname == 'example2.com'
pathToGo = (req.url).replace('www.','').replace('http://example2.com','')
request('http://localhost:8020'+pathToGo).pipe(res)
#Other
else
res.redirect '/404'
As you can see in Example2.com, I'm attempting to reverse proxy to another node instance on a different port. Overall it works perfectly, except for one issue. If the route on the other node instance changes (Redirects from example2.com/page1.html to example2.com/post5), the URL in the address bar doesn't change. Would anyone happen to have a nice workaround for this? Or maybe a better way to reverse proxy? Thanks!
In order to redirect the client, you should set the http-status-code to 3xx and send a location header.
I'm not familiar with request module but I believe it follows redirects by default.
On the other hand, you're piping the proxy-request's response to client's response object, discarding the headers and the status code. That's why the clients don't get redirected.
Here is a simple reverse HTTP proxy using the built-in HTTP client. It's written in javascript but you can easily translate it to coffeescript and use request module if you want.
var http = require('http');
var url = require('url');
var server = http.createServer(function (req, res) {
parsedUrl = url.parse(req.url);
var headersCopy = {};
// create a copy of request headers
for (attr in req.headers) {
if (!req.headers.hasOwnProperty(attr)) continue;
headersCopy[attr] = req.headers[attr];
}
// set request host header
if (headersCopy.host) headersCopy.host = 'localhost:8020';
var options = {
host: 'localhost:8020',
method: req.method,
path: parsedUrl.path,
headers: headersCopy
};
var clientRequest = http.request(options);
clientRequest.on('response', function (clientResponse) {
res.statusCode = clientResponse.statusCode;
for (header in clientResponse.headers) {
if (!clientResponse.headers.hasOwnProperty(header)) continue;
res.setHeader(header, clientResponse.headers[header]);
}
clientResponse.pipe(res);
});
req.pipe(clientRequest);
});
server.listen(80);
// drop root privileges
server.on('listening', function () {
process.setgid && process.setgid('nobody');
process.setuid && process.setuid('nobody');
});

Accessing response headers using node-http-proxy

I am trying to modify the response with the help of a proxy created using node-http-proxy.
However I am not able to access the response headers. I want to access the response headers since I would like to modify javascript files and send the modified javascript files to the client.
This is my code:
var httpProxy = require('http-proxy');
var url = require('url');
var i = 0;
httpProxy.createServer(function(req, res, next) {
var oldwriteHead = res.writeHead;
res.writeHead = function(code, headers) {
oldwriteHead.call(res, code, headers);
console.log(headers); //this is undefined
};
next();
}, function(req, res, proxy) {
var urlObj = url.parse(req.url);
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...");
});
writeHead() doesn't necessarily have to be called with an array of headers, write() can also send headers if necessary.
If you want to access headers (or set them), you can use this:
res.writeHead = function() {
// To set:
this.setHeader('your-header', 'your-header-value');
// To read:
console.log('Content-type:', this.getHeader('content-type'));
// Call the original method !!! see text
oldwriteHead.apply(this, arguments);
};
I'm using apply() to pass all the arguments to the old method, because writeHead() can actually have 3 arguments, while your code only assumed there were two.

Resources