只要三步,将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}`); });
现在重启服务就可以了
相关推荐
webgm 2020-08-16
yezitoo 2020-06-06
始作俑者 2020-01-19
Qimingweikun 2019-11-04
LorenLiu 2019-11-04
疯狂紫萧 2020-06-16
lei0 2020-11-02
igogo00 2020-07-04
iconhot 2020-06-26
88481456 2020-06-18
SelinaChan 2020-05-15
luckymaoyy 2020-04-25
80437700 2020-04-17
austindev 2020-04-07
我有一只小松鼠 2020-02-29
webfullStack 2020-02-15
binglingnew 2012-10-03
jinxiutong 2020-01-04