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中加入如下代码:
varapp = express();//使用nodejs自带的http、https模块
varhttps =require('https');
varhttp =require('http');
varfs =require('fs');
//根据项目的路径导入生成的证书文件
varprivateKey = fs.readFileSync(path.join(__dirname,'./certificate/private.pem'),'utf8');
varcertificate = fs.readFileSync(path.join(__dirname,'./certificate/ca.cer'),'utf8');
varcredentials = {key: privateKey, cert: certificate};
//创建http与HTTPS服务器
varhttpServer = http.createServer(app);
varhttpsServer = https.createServer(credentials, app);
//可以分别设置http、https的访问端口号
varPORT =8000;
varSSLPORT =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 Serverisrunningon:http://localhost:8000
HTTPS Serverisrunningon: https://localhost:8001
**打开浏览器访问:https://localhost:8001
**点击继续-高级--访问不安全链接:
**访问http服务器:http://localhost:8000