如果使用 JavaScript 生成 Azure Functions 并想要使用开发代理,请按照有关将开发代理与Node.js应用程序配合使用的一般指南进行操作。
重要
若要防止 Azure Functions 在启动时失败,请启动开发代理,不要将其注册为系统代理,可以使用--as-system-proxy false
选项,或在devproxyrc.json
文件中配置asSystemProxy
到false
。 如果将开发代理注册为系统代理,则 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.")'
为了能够在开发中使用开发代理而不是在生产环境中使用它之间轻松切换,最好使用环境变量在 Azure Functions 应用中配置代理。 更改 local.settings.json
文件以包含 HTTPS_PROXY
环境变量。 此外,禁用证书验证以允许 Azure Functions 应用信任开发代理使用的自签名证书。
{
"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 请求配置代理。
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
});