简体   繁体   中英

How to make nodejs request https server just like a browser?

I have an API server which already has a SSL cert from COMODO.

Everything works when I request through jQuery in the browser.

However, the https request in NodeJS always report { [Error: certificate not trusted] code: 'CERT_UNTRUSTED' }

I don't want to create self signed cert.

How do I fix it?

If you are making the request using the https module you need to enable the rejectUnauthorized option in the request. As per the official documentation: https://nodejs.org/api/https.html#https_https_request_options_callback

const https = require('https');

var options = {
  hostname: 'your-hostname',
  port: 443,
  path: '/the-path-to-access',
  method: 'GET',
  rejectUnauthorized: false // this is the line you need to add!
};

var req = https.request(options, (res) => {
  console.log('statusCode: ', res.statusCode);
  console.log('headers: ', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});
req.end();

req.on('error', (e) => {
  console.error(e);
});

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