国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 語(yǔ)言 > JavaScript > 正文

Express本地測(cè)試HTTPS的示例代碼

2024-05-06 15:33:38
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

我的環(huán)境

    亞馬遜(AWS)的一個(gè)ubuntu虛擬機(jī). node openssl

生成證書

輸入如下命令會(huì)在你的當(dāng)前文件夾生成localhost.key和localhost.cert.

openssl genrsa -out localhost.key 2048openssl req -new -x509 -key localhost.key -out localhost.cert -days 3650 -subj /CN=localhost

其中l(wèi)ocalhost為域名. 想要換成別的域名就直接把上面的所有l(wèi)ocalhost替換成你的域名.

以我為例, 我的虛擬機(jī)的域名是xxx.compute.amazonaws.com, 就以這個(gè)域名替換上面所有的localhost, 會(huì)生成, ec2-34-220-96-9.us-west-2.compute.amazonaws.com.key ec2-34-220-96-9.us-west-2.compute.amazonaws.com.cert兩個(gè)文件.

更新

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365

如果不想用密碼保護(hù)私鑰, 加上-nodes.

加上-subj '/CN=localhost'可以設(shè)置certificate的內(nèi)容. 將其中的localhost替換成你的域名.

參考:How to create a self-signed certificate with openssl?

代碼

想要運(yùn)行如下代碼, 需要先安裝包

npm initnpm i -S https express

創(chuàng)建文件index.js, 內(nèi)容如下.

#!/usr/bin/env nodevar https = require('https');var fs = require('fs');var express = require('express');var host = 'xxx.compute.amazonaws.com'; // Input you domain name here.var options = {  key: fs.readFileSync( './' + host + '.key' ),  cert: fs.readFileSync( './' + host + '.cert' ),  requestCert: false,  rejectUnauthorized: false};var httpApp = express();var app = express();app.get('/', function (req, res) { res.send('hi HTTPS');});httpApp.get('/', function (req, res) { res.send('hi HTTP');});httpApp.listen(80, function () { console.log('http on 80');});var server = https.createServer( options, app );server.listen( 443, function () {  console.log( 'https on 443' );} );

啟動(dòng)服務(wù)器

sudo node index.js

訪問(wèn)

瀏覽器中輸入http://xxx.compute.amazonaws.com/就會(huì)以80端口訪問(wèn)HTTP服務(wù)器. 顯示hi HTTP.

輸入https://xxx.compute.amazonaws.com/就會(huì)以443端口訪問(wèn)HTTPS服務(wù)器, 顯示hi HTTPS.

參考

Self-Signed, Trusted Certificates for Node.js & Express.js

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持錯(cuò)新站長(zhǎng)站。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 公主岭市| 忻城县| 卢龙县| 太保市| 西乡县| 托克托县| 元朗区| 民勤县| 鹤峰县| 成安县| 昌乐县| 于田县| 左贡县| 台中县| 平潭县| 海安县| 同仁县| 札达县| 苏尼特左旗| 盐池县| 抚顺县| 顺昌县| 泰州市| 肥西县| 侯马市| 阿拉尔市| 加查县| 伊金霍洛旗| 龙南县| 黔南| 临湘市| 海安县| 故城县| 曲沃县| 米泉市| 越西县| 内黄县| 卢湾区| 蕲春县| 大港区| 长兴县|