Skip to content

Instantly share code, notes, and snippets.

@rveitch
Created November 17, 2016 05:51
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rveitch/1b805b078a6e3cf1b2afd79acb9b984c to your computer and use it in GitHub Desktop.
Save rveitch/1b805b078a6e3cf1b2afd79acb9b984c to your computer and use it in GitHub Desktop.
Example Elasticsearch Proxy for Node.js
var express = require('express');
var request = require('request');
var app = express();
var port = Number(process.env.PORT || 3000);
var apiServerHost = (process.env.ELASTIC_URL || 'http://127.0.0.1:9200')
// Listen for requests on all endpoints
app.use('/', function(req, res, body) {
// short-circuit favicon requests for easier debugging
if (req.url != '/favicon.ico') {
console.log('req.method: ' + req.method);
console.log('req.url: ' + req.url);
// Request method handling: exit if not GET or POST
if ( ! (req.method == 'GET' || req.method == 'POST') ) {
errMethod = { error: req.method + " request method is not supported. Use GET or POST." };
console.log("ERROR: " + req.method + " request method is not supported.");
res.write(JSON.stringify(errMethod));
res.end();
return;
}
// pass the request to elasticsearch
var url = apiServerHost + req.url;
req.pipe(request({
uri : url,
auth : {
user : 'username',
pass : 'password'
},
headers: {
'accept-encoding': 'none'
},
rejectUnauthorized : false,
}, function(err, res, body) {
// you could do something here before returning the response
})).pipe(res); // return the elasticsearch results to the user
}
});
// Server Listen
app.listen(port, function () {
console.log('App server is running on http://localhost:' + port);
console.log('Heroku config variable - ELASTIC_URL: ' + process.env.ELASTIC_URL);
console.log('apiServerHost: ' + apiServerHost);
});
@jnsjunior
Copy link

Thanks, this example save me a lot of work!

@gilles14
Copy link

gilles14 commented Jul 6, 2021

Thanks, but what if I need to modify request body before sending it to elastic? Especially POST requests. In this case we need transform stream and pipe it one more time, but it doesn;t work for me.

var inherits = require('util').inherits;
var TransformStream = require('stream').Transform;

function UpperStream() {
    TransformStream.call(this);
}

inherits(UpperStream, TransformStream);
UpperStream.prototype._transform = function (chunk, encoding, cb) {
    cb(null, chunk);
};

let url = apiServerHost + req.url;
req.pipe(new UpperStream()).pipe(
   request({
         uri: url,
         headers: {
               'accept-encoding': 'none'
                    },
               rejectUnauthorized: false,
        })
).pipe(res); // return the elasticsearch results to the user

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment