pwa
依赖于Service Worker
,Manifest
,Push Notification
,其中Service Worker的主要功能如下:
- 后台数据的同步
- 从其他域获取资源请求
- 接受计算密集型数据的更新,多页面共享该数据
- 客户端编译与依赖管理
- 后端服务的hook机制
- 根据URL模式,自定义模板
- 性能优化
- 消息推送
- 定时默认更新
- 地理围栏
因为SW 的权利比较大,能够直接截取和返回用户的请求,所以要考虑安全性问题。这也是Service Worker
依赖于https
的原因。本篇先讲下本地如何提供一个https服务。
https服务主要依赖于证书文件
-
生成证书文件
(1)生成私钥key文件(下面的pathway表示你要保存的文件路径位置)
openssl genrsa 1024 > /pathway/private.pem
(2)通过上面生成的私钥文件生成CSR证书签名
openssl req -new -key /pathway/private.pem -out /pathway/csr.pem
会提示你输入一些信息
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) []:CN
State or Province Name (full name) []: #省
Locality Name (eg, city) []: #城市
Organization Name (eg, company) []: #公司名
Organizational Unit Name (eg, section) []: #可不填
Common Name (eg, fully qualified host name) []: #可不填
Email Address []: #邮箱
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []: #可不填
(3)通过上述私钥文件和CSR证书签名生成证书文件
openssl x509 -req -days 365 -in /pathway/csr.pem -signkey /pathway/private.pem -out /pathway/file.crt
到此证书文件生成完毕
证书文件.png
-
node中使用证书
(1)为了方便可以直接将文件copy到node项目中
image.png
(2)编写node服务代码
var express = require('express'); // 项目服务端使用express框架
var app = express();
var path = require('path');
var fs = require('fs');
//使用nodejs自带的http、https模块
var http = require('http');
var https = require('https');
//根据项目的路径导入生成的证书文件
var privateKey = fs.readFileSync(path.join(__dirname, './certificate/private.pem'), 'utf8');
var certificate = fs.readFileSync(path.join(__dirname, './certificate/file.crt'), 'utf8');
var credentials = {key: privateKey, cert: certificate};
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)浏览器中访问
image.png
可以看到我们已经成功使用https来访问我们的服务器,但是Chrome浏览器却显示红色的不安全,这是因为这个证书是我们自建的,没有经过第三方机构验证,所以会出现警告的提示。
参考自:https://blog.csdn.net/CHENYUFENG1991/article/details/60340006
网友评论