【问题标题】:Google Cloud REST API authentication exampleGoogle Cloud REST API 身份验证示例
【发布时间】:2020-10-17 12:03:33
【问题描述】:

我需要从 Google Cloud Function 发出此请求:

POST https://compute.googleapis.com/compute/v1/projects/project-id/zones/zone/instanceGroupManagers/instance-group-name/resize?size=new-size

根据这些文档:https://cloud.google.com/compute/docs/instance-groups/creating-groups-of-managed-instances#api_2

我了解如何分配 JSON 服务帐户密钥并使用 googleapi 库来完成。但在这种情况下,我需要该功能做的就是这个单一的请求。所以,我想简单地用fetch() 来做。授权书怎么写?

const url = `https://compute.googleapis.com/compute/v1/projects/${projectId}/zones/${zone}/instanceGroupManagers/${instanceGroupName}/resize?size=${size}`

const response = await fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  }
});
const responseJson = response.json();

【问题讨论】:

    标签: google-cloud-platform google-api authorization fetch


    【解决方案1】:

    您可以使用google auth library 获取正确的凭据并调用 API

    const {GoogleAuth} = require('google-auth-library');
    
    async function main() {
      const auth = new GoogleAuth({
        scopes: 'https://www.googleapis.com/auth/cloud-platform'
      });
      const client = await auth.getClient();
    
      const url = `https://compute.googleapis.com/compute/v1/projects/${projectId}/zones/${zone}/instanceGroupManagers/${instanceGroupName}/resize?size=${size}`
    
      const res = await client.request({ url: url,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      }
    });
      console.log(res.data);
    }
    
    main().catch(console.error);
    
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 2017-12-15
    • 2019-03-31
    • 2018-07-26
    • 2019-08-17
    • 1970-01-01
    相关资源
    最近更新 更多