nodejs中https请求失败,无报错

今天群里一位同学在做练习的时候,采用https例子:

// curl -k https://localhost:8000/
const https = require('https');
const fs = require('fs');

const options = {
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};

https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('hello world
');
}).listen(8000);

  在浏览器输入localhost:8000,回车,无法正常得到返回的'hello world',控制台也没有任何报错,通过浏览器的调试控制台我们可以看到:

get请求中的url路径是http而不是https,这是由于现阶段浏览器地址栏输入在没有明确是https或者http时,默认发送的是http请求,故而得不到响应。

其实在官网API的例子里也有提示这一点:

写这篇博文是为了让遇到这个问题的新手能够快速找到答案。

原文地址:https://www.cnblogs.com/yourstars/p/6652078.html