演習 - ストレージ アカウントを使用して静的 Web サイトをホストする
これで API がクラウドにデプロイされたので、Tailwind Traders エンジニアとして、クライアント コードを更新し、それをデプロイして、Azure Functions 向けの SignalR メッセージをサポートする必要があります。
クライアント アプリケーションを更新する
Visual Studio Code で、
./start/client/src/index.js
を開き、SignalR メッセージをリッスンするすべてのコードを置き換えます。 このコードは、HTTP 要求を含む初期ストック リストを取得し、SignalR 接続からの更新をリッスンします。 在庫が更新されると、クライアントは UI で株価を更新します。import './style.css'; import { BACKEND_URL } from './env'; const app = new Vue({ el: '#app', data() { return { stocks: [] } }, methods: { async getStocks() { try { const url = `${BACKEND_URL}/api/getStocks`; console.log('Fetching stocks from ', url); const response = await fetch(url); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status} - ${response.statusText}`); } app.stocks = await response.json(); } catch (ex) { console.error(ex); } } }, created() { this.getStocks(); } }); const connect = () => { const signalR_URL = `${BACKEND_URL}/api`; console.log(`Connecting to SignalR...${signalR_URL}`) const connection = new signalR.HubConnectionBuilder() .withUrl(signalR_URL) .configureLogging(signalR.LogLevel.Information) .build(); connection.onclose(() => { console.log('SignalR connection disconnected'); setTimeout(() => connect(), 2000); }); connection.on('updated', updatedStock => { console.log('Stock updated message received', updatedStock); const index = app.stocks.findIndex(s => s.id === updatedStock.id); console.log(`${updatedStock.symbol} Old price: ${app.stocks[index].price}, New price: ${updatedStock.price}`); app.stocks.splice(index, 1, updatedStock); }); connection.start().then(() => { console.log("SignalR connection established"); }); }; connect();
./start/client/index.html
開き、現在の DIV の代わりに次のコードをアプリの ID と共に貼り付けます。<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.4/css/bulma.min.css" integrity="sha256-8B1OaG0zT7uYA572S2xOxWACq9NXYPQ+U5kHPV1bJN4=" crossorigin="anonymous" /> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous"> <title>Stock Notifications | Enable automatic updates in a web application using Azure Functions and SignalR</title> </head> <body> <div id="app" class="container"> <h1 class="title">Stocks</h1> <div id="stocks"> <div v-for="stock in stocks" class="stock"> <transition name="fade" mode="out-in"> <div class="list-item" :key="stock.price"> <div class="lead">{{ stock.symbol }}: ${{ stock.price }}</div> <div class="change">Change: <span :class="{ 'is-up': stock.changeDirection === '+', 'is-down': stock.changeDirection === '-' }"> {{ stock.changeDirection }}{{ stock.change }} </span> </div> </div> </transition> </div> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js" integrity="sha256-chlNFSVx3TdcQ2Xlw7SvnbLAavAQLO0Y/LBiWX04viY=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/8.0.0/signalr.min.js"></script> <script src="bundle.js" type="text/javascript"></script> </body> </html>
このマークアップには、切り替え要素が含まれています。これにより、ストックデータの変化に応じて Vue.js が微妙なアニメーションを実行できるようになります。 株式が更新されたときに、タイルがフェードアウトし、すぐにまた表示されます。 このように、ページに在庫データがいっぱいの場合、ユーザーはどの株式が変更されたかを簡単に確認できます。
SignalR SDK を含めるために 、 bundle.jsへの参照のすぐ上に次のスクリプト ブロックを追加します。
<script src="https://cdn.jsdelivr.net/npm/@aspnet/signalr@1.0.3/dist/browser/signalr.js"></script>
クライアントの .env を更新する
start/client
という名前の.env
フォルダーに環境変数ファイルを作成します。BACKEND_URL
という名前の変数を追加し、ユニット 5 からコピーした値を追加します。BACKEND_URL=https://YOUR-FUNTIONS-APP-NAME.azurewebsites.net
Azure Static Web Apps リソースを作成してクライアントをデプロイする
Azure portal を開き、新しい Azure Static Web Apps リソースを作成します。
次の情報を使用して、リソース作成の [基本] タブに入力します。
名前 価値 サブスクリプション サブスクリプションを選択します。 リソースグループ リソース グループ stock-prototype
を使用します。静的 Web アプリ名 自分の名前を client
の後ろに追加します。 たとえば、client-jamie
のようにします。ホスティング プランの種類 [無料] を選択します。 デプロイ ソース [GitHub] を選択します。 組織 GitHub アカウントを選択する リポジトリ mslearn-advocates.azure-functions-and-signalr
を検索して選択します。[Branch]\(ブランチ) メイン ブランチを選択します。 Build Presets (ビルドのプリセット) [Vue.js] を選択します。 アプリの場所 「 /start/client
」と入力します。API の場所 空のままにします。 出力場所 「 dist
」と入力します。[ワークフロー ファイルのプレビュー] を選択して、デプロイ設定を確認します。 ビルドとデプロイの手順は次のようになります。
- name: Build And Deploy id: builddeploy uses: Azure/static-web-apps-deploy@v1 with: azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_123 }} repo_token: ${{ secrets.GITHUB_TOKEN }} # Used for Github integrations (i.e. PR comments) action: "upload" ###### Repository/Build Configurations - These values can be configured to match your app requirements. ###### # For more information regarding Static Web App workflow configurations, please visit: https://aka.ms/swaworkflowconfig app_location: "/solution/client" # App source code path api_location: "" # Api source code path - optional output_location: "dist" # Built app content directory - optional ###### End of Repository/Build Configurations ######
[ 閉じる] を選択して変更を保存します。
[ 確認と作成] を選択し、[ 作成 ] を選択してリソースを作成します。 デプロイが完了するまで待ってから次に進みます。
[ リソースに移動 ] を選択して、新しい Azure Static Web App リソースを開きます。
[ 概要 ] ページで、 URL 値をコピーします。 この値は、デプロイされた静的 Web アプリのベース URL です。
BACKEND_URL変数をリポジトリに追加する
ワークフローでは、 BACKEND_URL
環境変数をユニット 5 からデプロイされた Azure Functions アプリのベース URL に設定する必要があります。
サンプル リポジトリの GitHub フォーク用のブラウザーで、[ 設定] -> [セキュリティ] -> [シークレットと変数] -> Actions を選択します。
[ 変数] を選択し、[ 新しいリポジトリ変数] を選択します。
次の表を使用して変数を作成します。
名前 価値 BACKEND_URL デプロイされた Azure Functions アプリのベース URL。 URL は次の形式にする必要があります。 https://<FUNCTIONS-RESOURCE-NAME>.azurewebsites.net
[ 変数の追加] を選択して、変数をリポジトリに保存します。
GitHub デプロイ ワークフローを編集する
Visual Studio Code ターミナルで、フォーク (origin) から新しいワークフロー ファイルをプルダウンします。
git pull origin main
.github/workflows/azure-static-web-apps-*.yml
ファイルを開きます。ファイルの先頭にある
name
の値をClient
に変更します。ビルドと配置の手順を編集して、環境変数の
BACKEND_URL
プロパティを追加します。```yaml name: Client - Azure Static Web Apps CI/CD on: push: branches: - main pull_request: types: [opened, synchronize, reopened, closed] branches: - main jobs: build_and_deploy_job: if: github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.action != 'closed') runs-on: ubuntu-latest name: Build and Deploy Job steps: - uses: actions/checkout@v3 with: submodules: true lfs: false #Debug only - Did GitHub action variable get into workflow correctly? - name: Echo run: | echo "BACKEND_URL: ${{ vars.BACKEND_URL }}" - name: Build And Deploy id: builddeploy uses: Azure/static-web-apps-deploy@v1 with: azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_123 }} repo_token: ${{ secrets.GITHUB_TOKEN }} # Used for Github integrations (i.e. PR comments) action: "upload" ###### Repository/Build Configurations - These values can be configured to match your app requirements. ###### # For more information regarding Static Web App workflow configurations, please visit: https://aka.ms/swaworkflowconfig app_location: "/solution/client" # App source code path api_location: "" # Api source code path - optional output_location: "dist" # Built app content directory - optional ###### End of Repository/Build Configurations ###### env: BACKEND_URL: ${{ vars.BACKEND_URL }} close_pull_request_job: if: github.event_name == 'pull_request' && github.event.action == 'closed' runs-on: ubuntu-latest name: Close Pull Request Job steps: - name: Close Pull Request id: closepullrequest uses: Azure/static-web-apps-deploy@v1 with: azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_123 }} action: "close" ```
変更を保存してリポジトリにプッシュします。
git add . git commit -m "Add BACKEND_URL environment variable" git push origin main
GitHub フォーク リポジトリの [ アクション] タブを開き、デプロイを監視します。
関数アプリで CORS を更新する
既定では、関数アプリでは CORS 要求は許可されません。 静的 Web アプリからの要求を許可するように関数アプリを更新する必要があります。
Azure portal で、ユニット 5 で作成した Azure Functions アプリに移動します。
左側のメニューで、 API -> CORS を選択します。
[ Access-Control-Allow-Credentials を有効にする] を選択します。
静的 Web Apps リソース URL にコピーした値を追加します。
プロパティ 価値 許可されるオリジン デプロイされた静的 Web アプリのベース URL。 [ 保存] を 選択して CORS 設定を保存します。
クライアントのデプロイをテストする
ブラウザーで、デプロイされた静的 Web アプリの URL を使用してクライアントを開きます。
Azure portal で開発者ツールを開き、コンソールを見て、更新された在庫の SignalR データをいつ受信するかを確認します。 SignalR データは HTTP 要求でないため、更新は [ネットワーク] タブには表示されません。
おめでとうございます! SignalR で強化されたストックアプリをデプロイしました!