共用方式為


與 JavaScript Azure Functions 搭配使用「Dev Proxy」

如果您使用 JavaScript 建置 Azure Functions 並想要使用 Dev Proxy,請遵循搭配 Node.js 應用程式使用 Dev Proxy 的一般指引

這很重要

若要防止 Azure Functions 在啟動時失敗,請啟動 Dev Proxy,但不要將其註冊為系統 Proxy。可以使用 --as-system-proxy false 選項,或在 asSystemProxy 檔案中將 false 設定為 devproxyrc.json。 如果您將 Dev Proxy 註冊為系統 Proxy,Azure Functions 會在啟動時失敗,並出現類似下列的錯誤訊息:

Grpc.Core.RpcException: 'Status(StatusCode="Internal", Detail="Error starting gRPC call. HttpRequestException: Requesting HTTP version 2.0 with version policy RequestVersionOrHigher while unable to establish HTTP/2 connection.", DebugException="System.Net.Http.HttpRequestException: Requesting HTTP version 2.0 with version policy RequestVersionOrHigher while unable to establish HTTP/2 connection.")'

在開發中使用 Dev Proxy,並於生產環境中停用它之間輕鬆切換,您可以透過環境變數在 Azure Functions 應用程式中有效地設定 Proxy。 變更檔案 local.settings.json 以包含 HTTPS_PROXY 環境變數。 此外,請停用憑證驗證,讓 Azure Functions 應用程式信任 Dev Proxy 所使用的自我簽署憑證。

{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "node",
    "AzureWebJobsFeatureFlags": "EnableWorkerIndexing",
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "HTTPS_PROXY": "http://127.0.0.1:8000",
    "NODE_TLS_REJECT_UNAUTHORIZED": "0"
  }
}

在您的 Azure Functions 應用程式中,使用 process.env 對象來讀取環境變數,並設定 HTTP 要求的 Proxy。

import { app, HttpRequest, HttpResponseInit, InvocationContext } from "@azure/functions";
import fetch from 'node-fetch';
import { HttpsProxyAgent } from 'https-proxy-agent';

export async function MyFnHttpTrigger(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> {
    const options = process.env.HTTPS_PROXY ? { agent: new HttpsProxyAgent(process.env.HTTPS_PROXY) } : {};
    const resp = await fetch('https://jsonplaceholder.typicode.com/posts', options);
    const data = await resp.json();
    return {
      status: 200,
      jsonBody: data
    };
};

app.http('MyFnHttpTrigger', {
    methods: ['GET', 'POST'],
    authLevel: 'anonymous',
    handler: MyFnHttpTrigger
});