只要三步,將koa的node服務升級到https

開篇寫一堆無關緊要的內容都是耍流氓,因此咱們直接開始講升級步驟。npm

1、安裝必要的包
yarn add https fs koa-sslify
複製代碼

或者json

npm i -S https fs koa-sslify
複製代碼

https 用於啓動https服務
fs用於獲取讀取證書文件
koa-sslify 用於將http請求強制轉換爲https請求api

2、獲取證書

網上有不少教程了,能夠自行查閱。
我是在阿里雲下載免費證書(羅老師又不是不能用.jpg)。跨域

3、修改服務入口文件代碼

引入包bash

const https = require('https');
const fs = require('fs');
const enforceHttps = require('koa-sslify');
複製代碼

設置強制轉化http請求爲httpsapp

// Force HTTPS on all page
app.use(enforceHttps());
複製代碼

修改啓動服務語句cors

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}`);
});
複製代碼

貼個服務端入口完整代碼koa

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}`);
});
複製代碼

如今重啓服務就能夠了post

相關文章
相關標籤/搜索