mkcert:讓你在 localhost 開發也能用 https

mkcert 可以開發者快速產生 https 憑證,讓本地端 localhost 開發也能用https

httphttps 之間差異這裡就不贅述,對前端瀏覽器而言,串接後端 API 最常遇到的就是跨域 CORS 的問題,而不同協議 httphttps 彼此也有跨域問題。

通常 local 開發環境通常會是 http,以前筆者還菜菜的時候,不懂 localhost 怎麼會有需要 https 這個需求,直到我遇到 Yahoo Sign in 這種一定要 https 的 3rd 功能要串接....

總不能本機盲改串功能,deploy 上測試站才能測吧,為了做到在本機電腦也能正常開發,我們需要讓 localhost 變成 https 協定。

mkcert 在不同電腦環境、瀏覽器 (Chrome、Firefox) 的安裝指令略有一點點差異。
以下是筆者環境:

  • 電腦環境: Mac
  • 瀏覽器: Chrome
  • 後端: Node.js Express

安裝

首先打開 terminal 輸入

brew install mkcert

接著下

mkcert -install

接著 cd 切到自己的專案資料夾目錄,按照你的需求下對應指令

mkcert ${域名}

因為我們要產 localhost 的憑證,所以這裏下

mkcert localhost

就會在當前指向的資料夾產生 localhost-key.pemlocalhost.pem 兩個檔案

使用

接著就是要使用 localhost-key.pemlocalhost.pem
打開專案中 Node server 後端檔案,在上方加入 httpsfs 這兩包套件,這裡不解釋 requirehttpsfs 的功用,詳情自己看官方文件

const https = require('https');
const fs = require('fs');

接著用 fs 指向剛剛產的 pem 檔案,注意路徑不要用錯。

const options = {
  key: fs.readFileSync(`${路徑}/localhost-key.pem`),
  cert: fs.readFileSync(`${路徑}/localhost.pem`)
};

接著如果是用 Express, 那你的 Node.js code 「可能會類似」這樣的寫法

const app = express();
// ... 略
app.use(...);
// ... 略
app.get(...)
// ... 略
app.listen(2000, async ()=> {...})

原本的 code app.useapp.get 有的沒的 code 都不要動。
新加入這行:

const httpsServer = https.createServer(options, app);

https 這個 Node.js 套件 createServer ,多包一層在 app 上,
這麼做的目的,既可以繼續使用原本的 app express 該有的功能,也能使用被 https 擴充的功能。
接著在最下面的 app.listen code 這邊,我們要改使用包過的 httpsServer

把這段

app.listen(2000, async ()=> {...})

app.listen 改成 httpsServer.listen

httpsServer.listen(2000, async ()=> {...})

後面的 port 號 2000 ,和 async callback 都不動
接著存檔重啟 server,這時應該就能進 https://localhost:2000

參考

https://github.com/FiloSottile/mkcert
https://w3c.hexschool.com/blog/cd7b449b