只要三步,将koa的node服务升级到https

开篇写一堆可有可无的内容都是耍流氓,所以我们直接开始讲升级步骤。

一、安装必要的包
yarn add https fs koa-sslify

或者

npm i -S https fs koa-sslify

https 用于启动https服务
fs用于获取读取证书文件
koa-sslify 用于将http请求强制转换为https请求

二、获取证书

网上有很多教程了,可以自行查阅。
我是在阿里云下载免费证书(罗老师又不是不能用.jpg)。

三、修改服务入口文件代码

引入包

const https = require('https');
const fs = require('fs');
const enforceHttps = require('koa-sslify');

设置强制转化http请求为https

// Force HTTPS on all page
app.use(enforceHttps());

修改启动服务语句

const options = {
  key: fs.readFileSync('./app/ssl/ssl.key'),
  cert: fs.readFileSync('./app/ssl/ssl.pem')
};
https.createServer(options, app.callback()).listen(config.port, () => {
  // const host = server.address().address
  const host = config.host;
  const port = config.port;
  console.log(`应用实例,访问地址为 https://${host}:${port}`);
});

贴个服务端入口完整代码

const Koa = require('koa');
const cors = require('koa2-cors');
const koaStatic = require('koa-static');
const bodyParser = require('koa-bodyparser');
const path = require('path');
const https = require('https');
const fs = require('fs');
const enforceHttps = require('koa-sslify');
const config = require('./config/config');
const router2controller = require('./app/router2controller.js');
const history = require('./app/utils/middleware/connect-history-api-fallback.js');

const app = new Koa();
// 刷新后404找到路由(要放最上面)
app.use(history());

// 强制转换https
app.use(enforceHttps());

// 配置跨域、请求头
app.use(cors({
  origin: (ctx) => {
    return '*';
  },
  exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
  maxAge: 5,
  credentials: true,
  allowMethods: ['GET', 'POST', 'OPTIONS'],
  allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}));
// 将 post 请求和表单提交的查询字符串转换成对象,并挂在 ctx.request.body 上
app.use(bodyParser({
  enableTypes: ['json', 'form', 'text'], // 配置可解析的类型
}));
// 打包后静态资源访问路径
const staticPath = '../dist'
app.use(koaStatic(
  path.join(__dirname, staticPath)
));
// 路由处理
app.use(router2controller());

const options = {
  key: fs.readFileSync('./app/ssl/ssl.key'),
  cert: fs.readFileSync('./app/ssl/ssl.pem')
};
https.createServer(options, app.callback()).listen(config.port, () => {
  // const host = server.address().address
  const host = config.host;
  const port = config.port;
  console.log(`应用实例,访问地址为 https://${host}:${port}`);
});

现在重启服务就可以了

相关推荐