首页 > 编程语言 >How to enable HTTPS on a localhost Node.js Server All In One

How to enable HTTPS on a localhost Node.js Server All In One

时间:2023-09-19 20:24:01浏览次数:45  
标签:Node enable https req js pem key server localhost

How to enable HTTPS on a localhost Node.js Server All In One

locahost HTTPS

errors ❌

clientError =
 [Error: 4056C15DF87F0000:error:0A000416:SSL routines:ssl3_read_bytes:sslv3 alert certificate unknown:../deps/openssl/openssl/ssl/record/rec_layer_s3.c:1584:SSL alert number 46
] {
  library: 'SSL routines',
  reason: 'sslv3 alert certificate unknown',
  code: 'ERR_SSL_SSLV3_ALERT_CERTIFICATE_UNKNOWN'
}
# $ openssl req -nodes -new -x509 -keyout server.key -out server.cert
// Generating a 2048 bit RSA private key

$ openssl req -x509 -newkey rsa:2048 -keyout server_key_temp.pem -out server_cert.pem -days 365
// Generating a 2048 bit RSA private key
$ openssl rsa -in server_key_temp.pem -out server_key.pem
# phrase === 1234567
$ openssl req -x509 -sha256 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365

Generating a 4096 bit RSA private key
.......................++++
.................................................................................................................++++
writing new private key to 'key.pem'
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) []:CN
State or Province Name (full name) []:SH
Locality Name (eg, city) []:SH
Organization Name (eg, company) []:
Organizational Unit Name (eg, section) []:
Common Name (eg, fully qualified host name) []:
Email Address []:

$ openssl rsa -in key.pem -out decrypt_key.pem


自签名证书 localhost 不好使了 bug ❌

https://www.cnblogs.com/xgqfrms/p/13845919.html

solution ✅

Let's Encrypt - Free SSL/TLS Certificates

# OpenSSL TLS 1.3
$ openssl req -x509 -out localhost.crt -keyout localhost.key \
  -newkey rsa:2048 -nodes -sha256 \
  -subj '/CN=localhost' -extensions EXT -config <( \
   printf "[dn]\nCN=localhost\n[req]\ndistinguished_name = dn\n[EXT]\nsubjectAltName=DNS:localhost\nkeyUsage=digitalSignature\nextendedKeyUsage=serverAuth")

https://letsencrypt.org/zh-cn/docs/certificates-for-localhost/

demos

HTTPS 默认的端口 443 ✅ 自动重定向

https://localhost:443/api?id=1 => https://localhost/api?id=1

import https from 'node:https';
import fs from 'node:fs';
import express from 'express';
import chalk from 'chalk';

import bodyParser from 'body-parser';

const app = express();
const port = 443;
const options = {
  key: fs.readFileSync('./localhost.key'),
  cert: fs.readFileSync('./localhost.crt'),
};

// const options = {
//   // Error: error:1C800064:Provider routines::bad decrypt
//   // key: fs.readFileSync('./server_key_temp.pem'),
//   key: fs.readFileSync('./server_key.pem'),
//   cert: fs.readFileSync('./server_cert.pem'),
// };
// const options = {
//   // ❌ Error: error:1C800064:Provider routines::bad decrypt
//   // key: fs.readFileSync('./key.pem'),
//   key: fs.readFileSync('./decrypt_key.pem'),
//   cert: fs.readFileSync('./cert.pem'),
//   // key: fs.readFileSync('./key.pem', 'utf8'),
//   // cert: fs.readFileSync('./cert.pem', 'utf8'),
// };

// parse request `application/x-www-form-urlencoded`
// app.use(bodyParser.urlencoded({ extended: false }));
// parse request `application/json`
app.use(bodyParser.json());

app.get(`/api`, (req, res) => {
  console.log(`req.query`, req.query);
  // req.query { id: '1' }
  res.json({
    https: true,
    port,
  })
});

// https://localhost:443/api?id=1 => https://localhost/api?id=1
// HTTPS 默认的端口 443 ✅

app.post(`/api/:id`, (req, res) => {
  console.log(`req.params`, req.params);
  console.log(`req.body`, req.body);
  // req.query { id: '1' }
  // req.body { id: 7 }
  const {id} = req.params;
  res.json({
    https: true,
    port,
    id,
  });
});

/* 

const url = `https://localhost:443/api/1`;
const json = await fetch(url, {
  body: JSON.stringify({id: 7}),
  headers: {
    "Content-Type": "application/json",
  },
  method: "POST",
}).then(res => res.json());
console.log(`post json =`, json);

*/

const server = https.createServer(options, app);
server.listen(port, () => {
  // const color = chalk.green('Hello world!');
  const color = chalk.green.bgGreen('Hello world!');
  console.log(`color log`, color);
  console.log(`https server is running on: https://localhost:${port}/`);
  console.log(chalk.magenta(`[API]: `) + chalk.green('PORT : [ 443 ]'));
});

server.on("clientError", (error, socket) => {
  console.log(`❌ clientError =\n`, error);
});


image

This page is secure (valid HTTPS).

image

(

标签:Node,enable,https,req,js,pem,key,server,localhost
From: https://www.cnblogs.com/xgqfrms/p/17713600.html

相关文章

  • Jasper模板使用记录二——JSON文件数据源
    json文件数据源1.新建json文件,并将字段补充完整,示例如下:{ hosp_name:"医院", rows:[{ name:"姓名", age:12, }]}2.新建json数据源,如下:3.新建Jasper文件4.设置数据源,并导入数据源字段至Fields5.通过拖拽Paramter或Field至模板,进行模板设计......
  • Go每日一库之15:gojsonq
    简介在日常工作中,每一名开发者,不管是前端还是后端,都经常使用JSON。JSON是一个很简单的数据交换格式。相比于XML,它灵活、轻巧、使用方便。JSON也是RESTfulAPI推荐的格式。有时,我们只想读取JSON中的某一些字段。如果自己手动解析、一层一层读取,这就变得异常繁琐了。特别是在......
  • arcgis for js4.x自定义Graphic数组创建FeatureLayer添加标注
    varpoint=[{ "geometry":{ "x":116.820688, "y":33.974053, "spatialReference":{ "wkid":4326 } }, "......
  • JS push()方法
    定义和用法push()方法可向数组的末尾添加一个或多个元素,并返回新的长度。语法arrayObject.push(newelement1,newelement2,....,newelementX)参数描述newelement1必需。要添加到数组的第一个元素。newelement2可选。要添加到数组的第二个元素。newelementX可选。可添加多个元......
  • Java利用Jackson轻松处理JSON序列化与反序列化
    目录1.@JsonProperty2.@JsonFormat3.@JsonIgnore4.@JsonIgnoreProperties5.@JsonInclude6.@JsonTypeInfo和@JsonSubTypes7.@JsonView8.@JsonNaming9.@JsonSerialize和@JsonDeserialize10.@JsonAnyGetter和@JsonAnySetter11.@JsonIdentityInfo总结......
  • cookie json 请求头
    准备工作1.导入json依赖点击查看代码<!--jackson依赖--><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.15.2</version......
  • js/jquery 关于select 的一些操作
    1.如何设置默认选中呢设置默认选中可在option中添加selected="selected",具体举例如下:<optionvalue="2"selected="selected">test2</option><selectid="citySel"class="select"><optionvalue="......
  • 安装node、npm和vue3
    1.首先安装node和npmnode.js安装地址https://nodejs.org/en/download/2.下载完安装好后,打开终端命令验证是否安装成功node-vnpm-v3.安装vue3npminstall-g@vue/cli4.创建vue3项目npmcreate【your-project-name】这一指令将会安装并执行create-vue,它是......
  • Linux 安装Nodejs
    1.cd/usr/local/src/2.下载nodewgethttps://nodejs.org/dist/v15.4.0/node-v15.4.0-linux-x64.tar.xz3.解压文件tarxfnode-v15.4.0-linux-x64.tar.xz4.导航至解压目录cdnode-v15.4.0-linux-x65.运行node查看版本,确认是否安装成功:./bin/node-v6.设置node软链接:ln......
  • js removeRepeat 数组去重
    //数组不去重_this.incompleteData.map(e=>e.order_id).join(',')//数组去重varorder_ids=_this.incompleteData.map(e=>e.order_id).removeRepeat().join(','); ......