Nodejs 搭建https服务器(二)

来源:互联网 发布:php输出100以内的素数 编辑:程序博客网 时间:2024/06/06 02:05

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 .....

 

执行完毕后的目录如下:


3.2 配置文件

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

 

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 onhttp://localhost:8000

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

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

 

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

 

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

 

0 0
原创粉丝点击