Nodejs 搭建https服务器(二)

3. Node搭建https服务器

3.1 配置express项目

$ cd /Users/51testing/Desktop/https  

$ express HttpsService

....    install dependencies:     

 $ cd HttpsService && npm install     run the app:     

 $ DEBUG=httpsservice:* npm start

 $ cd HttpsService && npm install .....

 

执行完毕后的目录如下:

006zipb5zy7ayulJdFgda&690

3.2 配置文件

创建目录certificate,将创建的文件拖入进去,

006zipb5zy7ayummk6c40&690 

3.3 编写代码


express默认采用http协议,在bin/www目录下配置入口文件;
我们在app.js文件中配置https服务器, nodejs默认存在http与https模块,直接引用即可.

#app.js中加入如下代码:  

var app = express();  //使用nodejs自带的http、https模块

 var https = require('https');

 var http = require('http');

 var fs = require('fs');  

//根据项目的路径导入生成的证书文件 

var privateKey  = fs.readFileSync(path.join(__dirname, './certificate/private.pem'), 'utf8');

 var certificate = fs.readFileSync(path.join(__dirname, './certificate/ca.cer'), 'utf8');

var credentials = {key: privateKey, cert: certificate};

 //创建http与HTTPS服务器

 var httpServer = http.createServer(app);

 var httpsServer = https.createServer(credentials, app);

 //可以分别设置http、https的访问端口号 

var PORT = 8000;

var SSLPORT = 8001;  

//创建http服务器

 httpServer.listen(PORT, function() {     

console.log('HTTP Server is running on: http://localhost:%s', PORT); });  

//创建https服务器

 httpsServer.listen(SSLPORT, function() {     

console.log('HTTPS Server is running on: https://localhost:%s', SSLPORT); });  //可以根据请求判断是http还是https 

app.get('/', function (req, res) {     

if(req.protocol === 'https') {         

res.status(200).send('This is https visit!');     

}     else {        

 res.status(200).send('This is http visit!');    

 }

});

3.4 验证

启动服务:

$ node bin/www

 HTTP Server is running on: http://localhost:8000

 HTTPS Server is running on: https://localhost:8001

**打开浏览器访问: https://localhost:8001

006zipb5zy7ayuncgqf6b&690 

**点击继续-高级--访问不安全链接:

006zipb5zy7ayunF1p4fe&690 

**访问http服务器: http://localhost:8000

006zipb5zy7ayuodJZ95b&690 

转载于:https://my.oschina.net/u/2971691/blog/886277

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值