😀

Azure Static Web Apps に .NET 8 の Azure Functions を追加してみた

に公開

以前書いた下記の Azure Static Web Apps を参考に、Vite + Vue + Azure Functions を .NET 8 で試してみました。

https://qiita.com/mnrst/items/70f61d9a380b033afc03

フロントエンドの Vite + Vue をローカルで動かす

zsh
prefix=mnrswadev
region=eastasia

npm create vite@latest $prefix -- --template=vue-ts

cd $prefix

npm install

npm run dev

open http://localhost:5173/

バックエンドの Azure Functions を追加

zsh
func init api --worker-runtime dotnet-isolated --target-framework net8.0

cd api

func new --name Hello --template HttpTrigger

func start

cd ..

フロントエンドからバックエンドの API を呼び出すコードに変更

HelloWorld.vue
<script setup lang="ts">
import { ref } from 'vue'

defineProps<{ msg: string }>()

const count = ref(0)
</script>

<template>
  <h1>{{ msg }}</h1>

  <div class="card">
    <button type="button" @click="count++">count is {{ count }}</button>
  </div>

  <p v-if="message">{{ message }}</p>
</template>

<script lang="ts">
import { defineComponent } from 'vue';

export default defineComponent({
  data() {
    return {
      message: "" as string,
    };
  },
  async mounted() {
    try {
      const response = await fetch("/api/hello");
      if (response.ok) {
        const data = await response.text();
        this.message = data;
      }
    } catch (error) {
      console.error("API呼び出しエラー:", error);
    }
  },
});
</script>

<style scoped>
.read-the-docs {
  color: #888;
}
</style>

swa コマンドでフロントエンドとバックエンドを統合して動作確認

zsh
swa start http://localhost:5173 -i api

open http://localhost:4280

動作確認

下記赤枠に API 経由のレスポンステキストが表示されました。

swa-functions-01.png

参考

https://learn.microsoft.com/ja-jp/azure/static-web-apps/add-api?tabs=vanilla-javascript

Discussion