读取 Cloudflare Workers 无服务器函数中的 env 秘密

问题描述 投票:0回答:1

这是一个看似微不足道的请求,但有人知道如何读取 cloudflare 函数内部的工作人员机密吗?我看到很多相互矛盾的建议,并且 Cloudflare 文档并未真正展示如何在现实世界的示例中使用它。

node.js environment-variables serverless cloudflare-workers
1个回答
1
投票

根据

Cloudflare
,秘密将在无服务器函数中
env
fetch 对象中发送。因此,如果您将该参数添加到您的获取中,它们就会神奇地出现在那里。

环境变量的命名结构是自定义的。你自己设置一下。在我的示例中,

API_KEY
是我用作秘密名称的名称(您可以使用任何您想要的名称)。

Cloudflare 并没有真正向您展示完整的示例。下面的代码示例从 Webhook 调用,从该 Webhook 摄取数据有效负载,然后将数据有效负载发送到 API 端点。您的数据形状可能与此处显示的不同,因此请务必根据需要进行调整:

export default {
  async fetch(request, env) {
    if (request.method === 'POST') {
      const webhookData = await request.json();

      if (webhookData.event === 'your.param.here') {
        const memberInfo = webhookData.payload;

        const apiData = {
          apikey: env.API_KEY,  // Use the secret here
          email: memberInfo.email,
        };

        // Make the API call
        const apiResponse = await fetch('https://your.endpoint.here/v1/', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(apiData)
        });

        if (apiResponse.ok) {
          // API request was successful
          return new Response('Webhook received and API request sent!', { status: 200 });
        } else {
          // API request failed
          console.error('API request failed:', await apiResponse.text());
          return new Response('An error occurred.', { status: 500 });
        }
      } else {
        // Not the event we're interested in
        return new Response('Event not handled.', { status: 200 });
      }
    } else {
      return new Response('Expected a POST request.', { status: 400 });
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.