node.jselasticsearchpython-requestsbasic-authenticationunirest

self signed certificate in certificate chain error for nodejs API Basic authentication


I am trying to add data to my elastic search index using REST API and it works fine in POSTMAN. I also tried the same with a python script with request which is working.

But the same fails with nodejs. It is giving me self signed certificate in certificate chain error.

var unirest = require('unirest');
console.log("start");
var req = unirest('PUT', 'https://24.73.543.228:9001/accelerators/_doc/12')
  .headers({
    'Content-Type': 'application/json',
    'Authorization': 'Basic ZWxhc3RpYzpQYXNzd29yZEAxcjdcMjM0='
  })
  .send(JSON.stringify({"name":"ajj","type":"test","description":"khukhkd","created_date":"2021-02-18T20:20:41.560Z"}))
  .end(function (res) { 
    if (res.error) throw new Error(res.error); 
    console.log(res.raw_body);
  });

This is the error.

Error: Error: self signed certificate in certificate chain
    at C:\Users\Desktop\test.js:10:26
    at Request.handleRequestResponse [as _callback] (C:\Users\node_modules\unirest\index.js:444:15)
    at self.callback (C:\Users\Bittu.Raju\node_modules\request\request.js:185:22)
    at Request.emit (events.js:315:20)
    at Request.onRequestError (C:\Users\Bittu.Raju\node_modules\request\request.js:877:8)
    at ClientRequest.emit (events.js:315:20)
    at TLSSocket.socketErrorListener (_http_client.js:426:9)
    at TLSSocket.emit (events.js:315:20)
    at emitErrorNT (internal/streams/destroy.js:92:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)

Tried the basic authentication

auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

And tried using the auth variable in header still with same error.

Tried the same with Python requests and it works fine. How to make it work in nodejs.

import requests
from requests.auth import HTTPBasicAuth
import json
url="https://24.73.543.228:9001/accelerators/_doc/12"
print(url)
payload=dataJson[i]
print(payload)
payload=json.dumps(payload)
print(type(payload))
headers = {
  'Content-Type': 'application/json',
}
response = requests.request("PUT", url, headers=headers, data=payload,auth=HTTPBasicAuth('usern', 'Password@123'),verify=False)
print(response.text)

Solution

  • Since your certificate is self-signed, you can simply try to not verify it by calling strictSSL(false):

    var req = unirest('PUT', 'https://24.73.543.228:9001/accelerators/_doc/12')
      .strictSSL(false)       <---- add this line
      .headers({
        'Content-Type': 'application/json',
        'Authorization': 'Basic ZWxhc3RpYzpQYXNzd29yZEAxcjdcMjM0='
      })
      .send(JSON.stringify({"name":"ajj","type":"test","description":"khukhkd","created_date":"2021-02-18T20:20:41.560Z"}))
      .end(function (res) { 
         ...
    

    Another option is to specify the self-signed CA certificate using this other solution