最近许多的网站都开始强制使用 https,像前阵子碰到的 Facebook JavaScript SDK 也是如此,导致本地端测试很痛苦啊啊啊!爬文后发现有 mkcert 这神奇的东西,这边就记录一下该如何使用~
安装 mkcert
官方这边有提供 macOS 与 Windows 的安装方式
macOS
这边官方提供两种安装方式,使用 Homebrew 或是 MacPorts
<!-- Homebrew -->$ brew install mkcert$ brew install nss # if you use Firefox
<!-- MacPorts -->$ sudo port selfupdate$ sudo port install mkcert$ sudo port install nss # if you use Firefox
Windows
首先需要使先使用 PowerShell 安装 Chocolatey,这边须使用系统管理员身分执行
$ Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
Chocolatey 安装完成后,一样使用 PowerShell 系统管理员输入指令,这样就完成安装啰!
$ choco install mkcert
开始使用
本地端使用 https 总共有几个步骤
使用 mkcert 产生凭证,并将其加入信任清单将凭证绑定到指定网域,并产生金钥与凭证的档案进行专案设定接下来就让我们一步一步来吧!
第一步 - 产生凭证
因为我们刚刚已经安装好 mkcert,所以只需要一个指令便可产生凭证并加入信任清单
$ mkcert -install
第二步 - 产生档案
这边 mkcert 后面接输入绑定的网域,因为我们是本地端,所以输入 localhost
$ mkcert localhost
接下来便可以看到产生了两个档案,分别是金钥与凭证
/localhost.pem/localhost-key.pem
第三步 - 专案设定
这边分别介绍一下 Live Server、Vue CLI 与 Nuxt.js 三种设定方法
Live Server
官方这边有写到如何设定,基本上只要加上几行 code 就行了
{ "liveServer.settings.https": { "enable": true, "cert": "/Users/User/Desktop/map/localhost.pem", "key": "/Users/User/Desktop/map/localhost-key.pem", "passphrase": "12345" }}
cert 与 key 填上金钥与凭证的路径,接下来开启 localhost 就会看到 https 啰!
Vue CLI
Vue CLI 本身就包有 DevServer,可以直接于根目录新增 vue.config.js
档案做设定,方法如下
// vue.config.jsconst fs = require("fs");module.exports = { devServer: { https: { key: fs.readFileSync(`${__dirname}/src/assets/https/localhost-key.pem`), cert: fs.readFileSync(`${__dirname}/src/assets/https/localhost.pem`) } }};
金钥与凭证的路径就看自己放在哪边,这样就设定完成啰!
Nuxt.js
因为 Nuxt 有 SSR,所以我们必须写一个档案开启 server(这边使用 express)
首先资料夹结构如下,localhost 资料夹内有金钥、凭证与开启 server 的档案
接下来看到 localhost/index.js
,其实基本上都跟预设的大同小异
const express = require("express");const consola = require("consola");const { Nuxt, Builder } = require("nuxt");const app = express();// 多载入了以下两个 node.js 模组const https = require("https");const fs = require("fs");// 修改对应路径const config = require("../../nuxt.config.js");async function start() { const nuxt = new Nuxt(config); const { host, port } = nuxt.options.server; // 少了 production 模式的判断 try { const builder = new Builder(nuxt); await builder.build(); } catch (error) { console.error(error); return false; } // 新增 https 设定 const https_options = { key: fs.readFileSync(`${__dirname}/localhost-key.pem`), cert: fs.readFileSync(`${__dirname}/localhost.pem`) }; app.use(nuxt.render); // 开启 https server https.createServer(https_options, app).listen(port, host); consola.ready({ message: `Server listening on https://${host}:${port}`, badge: true });}start();
最后只要将 package.json
内的指令指向 server/localhost/index.js
即可
"scripts": { "dev": "cross-env NODE_ENV=development nodemon server/localhost/index.js --watch server",}
结语
一开始弄这个真的是被搞死啊...理解之后发现,原理还满简单的,在这边留下纪录给之后採坑的各位