在前面一篇文章中,使用openssl生成了免费证书后,我们现在使用该证书来实现我们本地node服务的https服务需求。假如我现在node基本架构如下:
|----项目 | |--- static # 存放html文件 | | |--- index.html # index.html | |--- node_modules # 依赖包 | |--- app.js # node 入口文件 | |--- package.json | |--- .babelrc # 转换es6文件
index.html 文件代码如下:
<!DOCTYPE html> <html> <head> <meta charset=utf-8> <meta name="referrer" content="never"> <title>nginx配置https</title> </head> <body> <div> <h2>欢迎使用https来访问页面</h2> </div> </body> </html>
app.js 代码如下:
const Koa = require('koa');
const fs = require('fs');
const path = require('path');
const router = require('koa-router')();
const koaBody = require('koa-body');
const static = require('koa-static');
const app = new Koa();
router.get('/', (ctx, next) => {
// 设置头类型, 如果不设置,会直接下载该页面
ctx.type = 'html';
// 读取文件
const pathUrl = path.join(__dirname, '/static/index.html');
ctx.body = fs.createReadStream(pathUrl);
next();
});
app.use(static(path.join(__dirname)));
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3001, () => {
console.log('server is listen in 3001');
});
package.json 代码如下;
{
"name": "uploadandload",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"dev": "nodemon ./app.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"fs": "0.0.1-security",
"koa": "^2.7.0",
"koa-body": "^4.1.0",
"koa-router": "^7.4.0",
"koa-send": "^5.0.0",
"koa-static": "^5.0.0",
"nodemon": "^1.19.0",
"path": "^0.12.7"
}
}
然后我在项目的根目录下执行 npm run dev 后,就可以在浏览器下访问 http://localhost:3001 了,但是为了我想使用域名访问的话,因此我们可以在 hosts文件下绑定下域名,比如叫 xxx.abc.com . hosts文件如下绑定:
127.0.0.1 xxx.abc.com
因此这个时候我们使用 http://xxx.abc.com:3001/ 就可以访问页面了,如下所示:

如上所示,我们就可以访问页面了,但是我们有没有发现,在chrome浏览器下 显示http请求是不安全的,因此这个时候我想使用https来访问就好了,网页的安全性就得到了保障,但是这个时候如果我什么都不做,直接使用https去访问的话是不行的,比如地址:https://xxx.abc.com:3001. 如下图所示:

我们知道使用https访问的话,一般是需要安全证书的,因此我们现在的任务是需要使用nginx来配置下安全证书之类的事情,然后使用https能访问网页就能达到目标。








