設定 Azure Static Web Apps 的應用程式設定

應用程式設定會保留可能會變更的組態值,例如資料庫 連接字串。 新增應用程式設定可讓您修改應用程式的組態輸入,而不需要變更應用程式程序代碼。

應用程式設定:

  • 可作為靜態 Web 應用程式的後端 API 的環境變數
  • 可用來儲存驗證組態中使用的 秘密
  • 待用加密
  • 會複製到 預備 和生產環境
  • 只能是英數位元、 ._

重要

本文所述的應用程式設定僅適用於 Azure 靜態 Web 應用程式的後端 API。

若要設定建置前端 Web 應用程式所需的環境變數,請參閱 建置組態

必要條件

設定本機開發的 API 應用程式設定

Azure Static Web Apps 中的 API 是由 Azure Functions 提供,可讓您在本機執行應用程式時,於local.settings.json檔案中定義應用程式設定。 此檔案會在組態的屬性中 Values 定義應用程式設定。

注意

local.settings.json檔案僅用於本機開發。 使用 Azure 入口網站 來設定生產環境的應用程式設定。

下列範例 local.settings.json 示範如何為 新增 值 DATABASE_CONNECTION_STRING

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "FUNCTIONS_WORKER_RUNTIME": "node",
    "DATABASE_CONNECTION_STRING": "<YOUR_DATABASE_CONNECTION_STRING>"
  }
}

Settings defined in the Values property can be referenced from code as environment variables. In Node.js functions, for example, they're available in the process.env object.

const connectionString = process.env.DATABASE_CONNECTION_STRING;

The local.settings.json file isn't tracked by the GitHub repository because sensitive information, like database connection strings, are often included in the file. Since the local settings remain on your machine, you need to manually configure your settings in Azure.

Generally, configuring your settings is done infrequently, and isn't required with every build.

設定應用程式設定

您可以透過 Azure 入口網站 或使用 Azure CLI 來設定應用程式設定。

使用 Azure 入口網站

Azure 入口網站 提供用來建立、更新和刪除應用程式設定的介面。

  1. 前往 Azure 入口網站

  2. 開啟靜態 Web 應用程式。

  3. 選取提要欄位中的 [ 組態 ]。

  4. 選取您要套用應用程式設定的環境。 您可以設定每個環境的應用程式設定。 當您建立提取要求時,會自動建立預備環境,然後在合併提取要求時升階為生產環境。

  5. 選取 [+ 新增 ] 以新增應用程式設定。 Azure Static Web Apps 組態檢視的螢幕快照

  6. 輸入 [名稱] 和 [值]。

  7. 選取 [確定]。

  8. 選取 [儲存]。

使用 Azure CLI

az staticwebapp appsettings使用 命令來更新 Azure 中的設定。

在終端機或命令列中,執行下列命令,以新增或更新名為 message 的設定,其值為 Hello world。 請務必以您的值取代佔位符 <YOUR_APP_ID>

az staticwebapp appsettings set --name <YOUR_APP_ID> --setting-names "message=Hello world"

Tip

You can add or update multiple settings by passing multiple name-value pairs to --setting-names.

View application settings with the Azure CLI

In a terminal or command line, execute the following command. Make sure to replace the placeholder <YOUR_APP_ID> with your value.

az staticwebapp appsettings list --name <YOUR_APP_ID>

Delete application settings with the Azure CLI

In a terminal or command line, execute the following command to delete a setting named message. Make sure to replace the placeholder <YOUR_APP_ID> with your value.

az staticwebapp appsettings delete --name <YOUR_APP_ID> --setting-names "message"

Tip

Delete multiple settings by passing multiple setting names to --setting-names.