本地主机的 Node.js https 服务器

标签 node.js ssl curl localhost

我关注了这篇文章:https://flaviocopes.com/express-https-self-signed-certificate/
用于为 localhost 测试我的 node.js 应用程序创建自签名证书。
但它不起作用:

node.js `v16.3.0`
openssl `(1.1.1f-1ubuntu2.3)` - `windows linux subsystem`
当我在浏览器中输入 https://localhost:3000它给了我错误:localhost uses an unsupported protocol. ERR_SSL_VERSION_OR_CIPHER_MISMATCH当我测试 curl -v https://localhost:3000它给了我这个:
*   Trying 127.0.0.1:17001...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 17001 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: /etc/ssl/certs
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.3 (IN), TLS alert, handshake failure (552):
* error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure
* Closing connection 0
curl: (35) error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure
我的代码:
const https = require('https')
const app = express()

app.get('/', (req, res) => {
  res.send('Hello HTTPS!')
})

https.createServer({
  key: fs.readFileSync('server.key'),
  cert: fs.readFileSync('server.cert')
}, app).listen(17001, () => {
  console.log('Listening...')
})

最佳答案

那篇文章(以及其他文章)包含我猜只有最新版本的 node.js 才会发生的错误。
读取文件时需要添加编码选项{encoding: "utf8"}如下:

https.createServer({
  key: fs.readFileSync('server.key', {encoding: "utf8"}),
  cert: fs.readFileSync('server.cert', {encoding: "utf8"})
}, app).listen(17001, () => {
  console.log('Listening...')
})

关于本地主机的 Node.js https 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68335744/

相关文章:

node.js - 启动 Electron 时将作业安排到队列中

node.js - 在 Node.js 中等待事件

javascript - 自定义 Yeoman 生成器无法覆盖文件

sql - Node.js 和 MSSQL 存储过程

ssl - 从类中使用 Xamarin Android HttpClient 错误

c++ - 添加 curl 库 C++

c++ - 如何使用 libcurl 从 github repo 下载 zip 文件?

apache - apache https 重定向错误(不受信任的连接)

c# - C# 中的 HTTPS 代理服务器

php curl 突然行为