简体   繁体   中英

Signing GET HTTP Requests to Amazon Elasticsearch Service

I need to call "Signing GET HTTP Requests to Amazon Elasticsearch Service" using lambda function.

I have already tried http package and it's working fine in http request

http.get(`http://search-"my_ES_service_name"-xxxxxxxxxxx-6fa27gkk4v3dugykj46tzsipbu.xx-xxxx-x.es.amazonaws.com/${event['index']}/doc/_search/?q=${event['keyParam']}`, 
  function(res) { 
    var body = '';
        res.on('data', function(d) {
            body += d;
        });

        res.on('end', function() {
            context.succeed(JSON.parse(body.replace(/\n|\r/g, ""))); //Remove and newline/linebreak chars
        });
  }).on('error', function(e) {
    console.log("Error: " + e.message);
    context.done(null, 'FAILURE');
  });
var AWS = require('aws-sdk');

exports.handler = function(event, context) {
  var region = 'xx-xxxx-x';
  var domain = 'http://search-"my_ES_service_name"-xxxxxxxxxxx-6fa27gkk4v3dugykj46tzsipbu.xx-xxxx-x.es.amazonaws.com';
  var index = event['index'];
  var type = `_doc/_search`;

  var endpoint = new AWS.Endpoint(domain);
  var request = new AWS.HttpRequest(endpoint, region);
  request.method = 'GET';
  request.path += index + '/' + type+'?q=_doc_key_here:_doc_key_value';
  request.headers['host'] = domain;
  > e.g. URL genrate like: http://search-"my_ES_service_name"-xxxxxxxxxxx-6fa27gkk4v3dugykj46tzsipbu.xx-xxxx-x.es.amazonaws.com/node-test/doc/_search/?q=user_name:johndoe

  var credentials = new AWS.EnvironmentCredentials('AWS');
  var signer = new AWS.Signers.V4(request, 'es');
  signer.addAuthorization(credentials, new Date());

  var client = new AWS.HttpClient();
  client.handleRequest(request, null, function(response) {
    console.log("response: ",response.statusCode);
    var responseBody = '';
    response.on('data', function (chunk) {
      responseBody += chunk;
    });
    response.on('end', function (chunk) {
      console.log('Response body: ' + responseBody);
      context.succeed(responseBody)
    });
  }, function(error) {
    console.log('Error: ' + error);
    context.done(error);
  });
}

when I'm trying to call "Signing GET HTTP Requests" using above function, then it's thrown me the following error:

response: 400 Bad Request

Only one thing is missing here, I have added encodeURI() in request and it works fine for me

var index = event['index'];
var type = `_doc/_search?q=_doc_key_here:_doc_key_value`;
request.method = 'GET';
request.path += index + '/' + encodeURI(type);

I hope it will help other guys

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM