nodejs - error self signed certificate in certific

2019-04-29 08:11发布

问题:

I am facing a problem with client side https requests.

A snippet can look like this:

var fs = require('fs');
var https = require('https');

var options = {
    hostname: 'someHostName.com',
    port: 443,
    path: '/path',
    method: 'GET',
    key: fs.readFileSync('key.key'),
    cert: fs.readFileSync('certificate.crt')
}

var requestGet = https.request(options, function(res){
    console.log('resObj', res);
}

What I get is Error: self signed certificate in certificate chain.

When I use Postman I can import the client certificate and key and use it without any problem. Is there any solution available?? I would also like to be given some lights on how postman handles the certificates and works.

回答1:

You need to add NODE_TLS_REJECT_UNAUTHORIZED='0' as an environment variable.



回答2:

You can write command npm config set strict-ssl=false



回答3:

Turning off verification is quite a dangerous thing to do. Much better to verify the certificate.

You can pull the Certificate Authority certificate into the request with the ca key of the options object, like this:

let opts = {
    method: 'GET',
    hostname: "localhost",
    port: listener.address().port,
    path: '/',
    ca: await fs.promises.readFile("cacert.pem")
  };

https.request(opts, (response) => { }).end();

I put a whole demo together of this so you can see how to construct SSL tests.

It's here.