使用 Azure Functions 將 API 新增至 Azure 靜態 Web Apps 預覽版Add an API to Azure Static Web Apps Preview with Azure Functions

您可以透過與 Azure Functions 的整合,將無伺服器 API 新增至 Azure 靜態 Web Apps。You can add serverless APIs to Azure Static Web Apps via integration with Azure Functions. 本文示範如何將 API 新增至 Azure 靜態 Web Apps 網站,並在其中進行部署。This article demonstrates how to add and deploy an API to an Azure Static Web Apps site.

PrerequisitesPrerequisites

建立 Git 存放庫Create a Git repository

下列步驟示範如何建立新的存放庫,並將檔案複製到您的電腦。The following steps demonstrate how to create a new repository and clone the files to your computer.

  1. 請確定您已登入 GitHub,然後流覽至 https://github.com/staticwebdev/vanilla-basic/generate 以建立新的存放庫。Make sure you are logged in to GitHub and, navigate to https://github.com/staticwebdev/vanilla-basic/generate to create a new repository.

  2. 在 [存放庫名稱] 方塊中,輸入 my-vanilla-apiIn the Repository name box, enter my-vanilla-api.

  3. 按一下 [從範本建立存放庫]。Click Create repository from template.

    從 vanilla-basic 建立新的存放庫

建立專案之後,請在瀏覽器中複製新存放庫的 URL。Once your project is created, copy the URL in your browser for the new repository. 您可以在 Visual Studio Code 中使用此 URL,以複製 Git 存放庫。You use this URL in Visual Studio Code to clone the Git repository.

  1. F1 鍵,在命令選擇區中開啟命令。Press F1 to open command in the Command Palette.

  2. 將 URL 貼到 Git:複製 提示字元,然後按 Enter 鍵。Paste the URL into the Git: Clone prompt, and press Enter.

    使用 Visual Studio Code 複製 GitHub 專案

    遵循提示來選取要複製專案的存放庫位置。Follow the prompts to select a repository location to clone the project.

建立 APICreate the API

接下來,您會建立 Azure Functions 專案作為應用程式的 API。Next, you create an Azure Functions project as the application's API.

  1. my-vanilla-api 專案中,建立名為 api 的子資料夾。Inside the my-vanilla-api project, create a sub-folder named api.

  2. F1 鍵以開啟命令選擇區Press F1 to open the Command Palette

  3. 輸入 Azure Functions:建立新專案...Type Azure Functions: Create New Project...

  4. EnterPress Enter

  5. 選擇 [瀏覽]Choose Browse

  6. 選取 api 資料夾做為專案工作區的目錄Select the api folder as the directory for your project workspace

  7. 選擇 [選取]Choose Select

    螢幕擷取畫面:顯示 P I 資料夾和 [選取] 按鈕。

  8. 依照提示提供下列資訊:Provide the following information at the prompts:

    • 選取語言:選擇 JavaScriptSelect a language: Choose JavaScript
    • 選取您的專案第一個函式的範本:選擇 HTTP 觸發程序Select a template for your project's first function: Choose HTTP trigger
    • 提供 函式名稱:輸入 GetMessageProvide a function name: Enter GetMessage
    • 授權層級 選擇 [匿名],讓任何人都能呼叫您的函式端點。Authorization level: Choose Anonymous, which enables anyone to call your function endpoint.

Visual Studio Code 會產生具有 HTTP 觸發函式的 Azure Functions 專案。Visual Studio Code generates an Azure Functions project with an HTTP triggered function.

您的應用程式現在具有類似下列範例的專案結構。Your app now has a project structure similar to the following example.

├── api
│   ├── GetMessage
│   │   ├── function.json
│   │   ├── index.js
│   │   └── sample.dat
│   ├── host.json
│   ├── local.settings.json
│   ├── package.json
│   └── proxies.json
├── index.html
├── readme.md
└── styles.css

接下來,您將變更函式, GetMessage 以將訊息傳回至前端。Next, you'll change the GetMessage function to return a message to the front-end.

  1. GetMessage使用下列程式碼更新 Api/GetMessage/index.js 下的函式。Update the GetMessage function under api/GetMessage/index.js with the following code.

    module.exports = async function (context, req) {
      context.res = {
        body: {
          text: "Hello from the API"
        }
      };
    };
    
  2. 使用下列設定來更新 api/GetMessage/function.json 底下的 GetMessage 組態。Update the GetMessage configuration under api/GetMessage/function.json with the following settings.

    {
      "bindings": [
        {
          "authLevel": "anonymous",
          "type": "httpTrigger",
          "direction": "in",
          "name": "req",
          "methods": [
            "get"
          ],
          "route": "message"
        },
        {
          "type": "http",
          "direction": "out",
          "name": "res"
        }
      ]
    }
    

使用上述設定,API 端點為:With the above settings, the API endpoint is:

  • 對函式發出 HTTP 要求時觸發Triggered when an HTTP request is made to the function
  • 適用於所有要求,不論驗證狀態為何Available to all requests regardless of authentication status
  • 透過 /api/message 路由公開Exposed via the /api/message route

在本機執行 APIRun the API locally

Visual Studio Code 可與 Azure Functions Core Tools 整合,讓您能夠先在本機開發電腦上執行此專案,再發佈至 Azure。Visual Studio Code integrates with Azure Functions Core Tools to let you run this project on your local development computer before you publish to Azure.

提示

在繼續之前,請確定您已安裝 必要條件 區段中所列的所有資源。Make sure you have all the resources listed in the prerequisites section installed before proceeding.

  1. F5 以啟動函式應用程式來執行函式。Run the function by pressing F5 to start the Functions app.

  2. 如果您尚未安裝 Azure Functions Core Tools,請在提示字元中選取 [安裝]。If Azure Functions Core Tools isn't already installed, select Install at the prompt.

    Core Tools 會在 終端 機面板中顯示正在執行之應用程式的輸出。The Core Tools shows output from the running application in the Terminal panel. 在輸出中,您可以查看在本機執行之 HTTP 觸發函式的 URL 端點。As a part of the output, you can see the URL endpoint of your HTTP-triggered function running locally.

    螢幕擷取畫面顯示 [終端機] 索引標籤,您可以在其中看到 U R L。

  3. 當核心工具執行時,流覽至下列 URL,以確認 API 是否正確執行: http://localhost:7071/api/messageWith Core Tools running, navigate to the following URL to verify the API is running correctly: http://localhost:7071/api/message.

    瀏覽器中的回應看起來應該類似下列範例:The response in the browser should look similar to the following example:

    Alt textScreenshot 會在瀏覽器中顯示文字回應。

  4. Shift + F5 以停止調試會話。Press Shift + F5 to stop the debugging session.

從應用程式呼叫 APICall the API from the application

當部署至 Azure 時,對 API 的要求會自動路由傳送至函式應用程式,以取得傳送至路由的要求 apiWhen deployed to Azure, requests to the API are automatically routed to the Functions app for requests sent to the api route. 在本機工作時,您必須將應用程式設定設定為對本機 API 的 proxy 要求。Working locally, you have to configure the application settings to proxy requests to the local API.

本機 ProxyLocal proxy

您可以設定 Live Server Visual Studio Code 擴充功能的 Proxy,將 /api 的所有要求路由至 http://127.0.0.1:7071/api 的執行中 API 端點。You can configure a proxy for the Live Server Visual Studio Code extension that routes all requests to /api to the running API endpoint at http://127.0.0.1:7071/api.

  1. 開啟 .vscode/settings.json 檔案。Open the .vscode/settings.json file.

  2. 新增下列設定以指定 Live Server 的 Proxy。Add the following settings to specify a proxy for Live Server.

    "liveServer.settings.proxy": {
       "enable": true,
       "baseUri": "/api",
       "proxyUri": "http://127.0.0.1:7071/api"
    }
    

    此組態最好儲存在專案設定檔中,而不是使用者設定檔中。This configuration is best saved in project settings file, as opposed to in the user settings file.

    使用專案設定可確保 Proxy 不會套用至 Visual Studio Code 中開啟的所有其他專案。Using project settings assures the proxy isn't applied to all other projects opened in Visual Studio Code.

更新 HTML 檔案以存取 APIUpdate HTML files to access the API

  1. 接下來,使用下列程式碼更新 index.html 檔案的內容,以從 API 函式擷取文字並將其顯示在螢幕上:Next, update the content of the index.html file with the following code to fetch the text from the API function and display it on the screen:

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <link rel="stylesheet" href="styles.css">
      <title>Vanilla JavaScript App</title>
    </head>
    
    <body>
      <main>
        <h1>Vanilla JavaScript App</h1>
        <p>Loading content from the API: <b id="name">...</b></p>
      </main>
    
      <script>
        (async function() {
          let { text } = await( await fetch(`/api/message`)).json();
          document.querySelector('#name').textContent = text;
        }())
      </script>
    </body>
    
    </html>
    
  2. F5 以啟動 API 專案。Press F5 to start the API project.

  3. F1 鍵,然後選擇 [Live Server:開啟即時伺服器] ,以啟動即時伺服器。Press F1 and choose Live Server: Open with Live Server.

    您現在應該會在網頁中看到 API 訊息。You should now see the API message in the web page.

    螢幕擷取畫面:在瀏覽器中顯示 P I 訊息。

    注意

    您可以使用其他 HTTP 伺服器或 Proxy 來提供 index.html 檔案。You can use other HTTP servers or proxies to serve the index.html file. 將無法從 file:/// 存取 index.htmlAccessing the index.html from file:/// will not work.

  4. Shift + F5 以停止 API 專案。Press Shift + F5 to stop the API project.

認可及推送您對 GitHub 的變更Commit and push your changes to GitHub

使用 Visual Studio Code 來認可您對遠端 Git 存放庫的變更並加以推送。Using Visual Studio Code, commit and push your changes to the remote git repository.

  1. F1 鍵以開啟命令選擇區Press F1 to open the Command Palette
  2. 輸入 Git:全部認可Type Git: Commit All
  3. 新增認可訊息,然後按 enterAdd a commit message and press Enter
  4. 按下 F1Press F1
  5. Git: push 中輸入,然後按 enterType in Git: push and press Enter

建立靜態 Web 應用程式Create a static web app

  1. 瀏覽至 Azure 入口網站Navigate to the Azure portal
  2. 按一下 [建立資源]Click Create a Resource
  3. 搜尋 靜態 Web 應用程式Search for Static Web App
  4. 按一下 [ 靜態 Web 應用程式 (預覽])Click Static Web App (Preview)
  5. 按一下 [建立] Click Create

接下來,新增應用程式特定的設定。Next, add the app-specific settings.

  1. 選取您的 Azure 訂用帳戶Select your Azure subscription
  2. 選取或建立新的 [資源群組]Select or create a new Resource Group
  3. 將應用程式命名為 my-vanilla-apiName the app my-vanilla-api.
  4. 選取最靠近您的 [區域]Select Region closest to you
  5. 選取 [免費] SKUSelect the Free SKU
  6. 按一下 [使用 GitHub 登入] 按鈕,並向 GitHub 進行驗證Click the Sign-in with GitHub button and authenticate with GitHub
  7. 選取您慣用的 [組織]Select your preferred Organization
  8. 從 [存放庫] 下拉式選單中,選取 my-vanilla-apiSelect my-vanilla-api from the Repository drop-down
  9. 從 [分支] 下拉式選單中,選取 [主要]Select master from the Branch drop-down
  10. 從 [ 組建 預設值] 下拉式清單中,選取您選擇的架構來建立組建Select the framework of your choice for build configuration from the Build Presets drop-down

這些欄位會反映應用程式類型的預設專案結構。These fields will reflect the app type's default project structure. 變更值以符合您的應用程式。Change the values to suit your app.

接下來,新增下列組建詳細資料。Next, add the following build details.

  1. 輸入 / 應用程式位置Enter / for the App location.

  2. 在 [API 位置] 方塊中,輸入 apiEnter api in the Api location box.

  3. 清除 [應用程式成品位置] 的預設值,並將此方塊保留空白。Clear the default value out of the App artifact location, leaving the box empty.

  4. 按一下 [檢閱 + 建立]。Click Review + create.

  5. 按一下 [建立] 按鈕Click the Create button

    一旦您按一下 [ 建立 ] 按鈕,Azure 就會執行兩項作業。Once you click the Create button, Azure does two things. 首先,會建立基礎雲端服務以支援應用程式。First, the underlying cloud services are created to support the app. 接下來,背景進程會開始建立及部署應用程式。Next, a background process begins to build and deploy the application.

  6. 按一下 [ 移至資源 ] 按鈕,以帶您前往 web 應用程式的 [總覽 ] 頁面。Click the Go to Resource button to take you to the web app's Overview page.

    當應用程式是在背景中建立時,您可以按一下包含連結的橫幅來查看組建狀態。As the app is being built in the background, you can click on the banner which contains a link to view the build status.

    GitHub 工作流程

  7. 部署完成後,ou 可以按一下 [總覽] 頁面上顯示的 URL 連結,以流覽至 web 應用程式。Once the deployment is complete, ou can navigate to the web app, by clicking on the URL link shown on the Overview page.

    從 Azure 入口網站存取靜態應用程式 URL

清除資源Clean up resources

如果您不想要保留此應用程式以供進一步使用,可以使用下列步驟來刪除 Azure 靜態 Web 應用程式及其相關資源。If you don't want to keep this application for further use, you can use the following steps to delete the Azure Static Web App and its related resources.

  1. 瀏覽至 Azure 入口網站Navigate to the Azure portal
  2. 在頂端的搜尋列中,輸入 資源群組In the top search bar, type Resource groups
  3. 按一下 [資源群組]Click Resource groups
  4. 選取 myResourceGroupSelect myResourceGroup
  5. 在 [myResourceGroup] 頁面上,確定所列出的資源是您想要刪除的項目。On the myResourceGroup page, make sure that the listed resources are the ones you want to delete.
  6. 選取 [刪除]Select Delete
  7. 在文字方塊中輸入 myResourceGroupType myResourceGroup in the text box
  8. 選取 [刪除] 。Select Delete.

後續步驟Next steps