0

Here I have a working curl command as follow.

the curl uses for searching elastic-search.

curl -X GET -H 'Content-Type:application/json' -u '(my_id):(my_password)' https://www.example.com/(elastic-search_node_name)/_search -d '
{"query":{"bool":{"must":[{"term":{"main.message.neworder":true}}],"must_not":[],"should":[]}},"from":0,"size":10,"sort":[],"aggs":{}}'

I'm trying to convert it to work in node.js(with using axio, request or node-libcurl)

But I don't know where to put authentication(-u option) and extra options such as elastic_search_node.

Could anyone please give me some advice to solve this issue?

Jin Park
  • 371
  • 1
  • 9
  • 23
  • If you use request, these should help: https://www.npmjs.com/package/request#http-authentication or https://www.haykranen.nl/2011/06/21/basic-http-authentication-in-node-js-using-the-request-module/ – wakakak Aug 01 '19 at 03:15
  • You can add an Authorization header - https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization – David Brossard Aug 01 '19 at 03:24
  • Possible duplicate of [How to use http.client in Node.js if there is basic authorization](https://stackoverflow.com/questions/3905126/how-to-use-http-client-in-node-js-if-there-is-basic-authorization) – David Brossard Aug 01 '19 at 03:24

1 Answers1

0

With node-libcurl it becomes this:

const { Curl } = require('node-libcurl')

const data = {
  query: {
    bool: {
      must: [{ term: { "main.message.neworder": true } }],
      must_not: [],
      should: [],
    },
  },
  from: 0,
  size: 10,
  sort: [],
  aggs: {},
}
const dataJSON = JSON.stringify(data)

const curl = new Curl
curl.setOpt('URL', 'https://www.example.com/(elastic-search_node_name)/_search')
curl.setOpt('USERPWD', '(my_id):(my_password)')
curl.setOpt('POSTFIELDS', dataJSON)
curl.setOpt('CUSTOMREQUEST', 'GET')
curl.setOpt('HTTPHEADER',
  ['Content-Type: application/json'])

curl.on("end", function (statusCode, data, headers) {
  console.info(statusCode)
  console.info('---')
  console.info(data.length)
  console.info('---')
  console.info(this.getInfo('TOTAL_TIME'))

  this.close()
})

curl.on('error', function(error) => {
  console.error(error)
  this.close()
})
curl.perform()

Or if you prefer async/await:

const { curly } = require('node-libcurl');

const data = {
  query: {
    bool: {
      must: [{ term: { "main.message.neworder": true } }],
      must_not: [],
      should: [],
    },
  },
  from: 0,
  size: 10,
  sort: [],
  aggs: {},
}
const dataJSON = JSON.stringify(data)

async function doRequest() {
  const { statusCode, data, headers } = await curly('https://www.example.com/(elastic-search_node_name)/_search', {
    customRequest: 'GET',
    httpHeader: ['Content-Type: application/json'],
    postFields: dataJSON,
    userPwd: '(my_id):(my_password)',
  })
  console.log(statusCode, data, headers)
}
doRequest()
jonathancardoso
  • 11,737
  • 7
  • 53
  • 72