0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Expressでhttpsを使用する方法

Last updated at Posted at 2025-03-02

はじめに

こんにちは!高校生でプログラミング勉強中のCureSabaです。

今回はTwitchのcallbackサーバーを作成しようと思った際、ERR_SSL_PROTOCOL_ERRORが出てアクセスできなかったのでexpressでhttpsを使用する方法をまとめてみました。

証明書作成

今回は開発環境用の自己署名とサーバー用の証明書の2つを作る方法を解説します

localhost用の証明書

まずはlocalhost証明書からです

opensslがインストールされた環境で下記のコマンドを実行し有効期限10年の自己証明書を作成します

openssl req -x509 -nodes -days 3650 -newkey rsa:2048 -keyout privkey.pem -out fullchain.pem -subj "/CN=localhost"

サーバー用証明書

環境はubuntuを使用しています

certbotインストール

今回はcloudflare dnsを使用して認証を行うのでcertbotとcloudflareプラグインをインストールします

sudo apt-get install certbot
sudo apt-get install python3-certbot-dns-cloudflare

cloudflare tokenの取得

cloudflareダッシュボードの左側からアカウントの管理>アカウント APIトークンを選択し
image.png
トークンを作成する>APIトークンテンプレート内のゾーンDNSを編集する>テンプレートを使用する
image.png

下記画像のselect部を証明書を取得したいドメインに設定>概要に進む>トークンを作成するからトークンをコピーする
image.png

APIキーの入ったConfigを作成する

以下のコマンドのAPI TOKENを先ほど取得したトークンに置き換える

sudo touch /etc/letsencrypt/cloudflare.ini
echo 'dns_cloudflare_api_token=API TOKEN' | sudo tee /etc/letsencrypt/cloudflare.ini
sudo chmod 600 /etc/letsencrypt/cloudflare.ini

証明書を取得する

以下のコマンドを実行して証明書を取得します

sudo certbot certonly --dns-cloudflare --dns-cloudflare-credentials /etc/letsencrypt/cloudflare.ini -m mail@example.com -d example.com -d *.example.com

生成した証明書は/etc/letsencrypt/live/yourdomain.comに保存されます

コード作成

コードを作成していきます

元のコード例

const express = require('express');
const app = express();

app.get('/', (req, res) => {
    res.send('Hello World!');
});

const server = app.listen(3000, () => {
    const host = server.address().address;
    const port = server.address().port;
    console.log('Example app listening at http://%s:%s', host === '::' ? 'localhost' : host, port);});

書き換え

https.createServer(options, requestListener)を用いてhttps.Serverオブジェクトを作成しその後普段と同様にlisten()で実行できます

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

const app = express();

// 証明書と秘密鍵を読み込む
const privateKey = fs.readFileSync('path_to_cert/privkey.pem', 'utf8');
const certificate = fs.readFileSync('path_to_cert/fullchain.pem', 'utf8');

const credentials = { key: privateKey, cert: certificate };

// ルートパスへのリクエストに対するレスポンス
app.get('/', (req, res) => {
    res.send('Hello, HTTPS world!');
});

// HTTPSサーバーの作成
const httpsServer = https.createServer(credentials, app);

httpsServer.listen(3000, () => {
    const host = httpsServer.address().address;
    const port = httpsServer.address().port;
    console.log('Example app listening at https://%s:%s', host === '::' ? 'localhost' : host, port);
});

終わりに

もし、この記事が役に立ったと思ったら、ぜひコメントやシェアをお願いします。また、質問や改善点などがあれば気軽にコメントしてください!

それでは、良いプログラミングライフを!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?