如何使用 Polymer 正确验证 Google 视觉 API

How to Properly Authenticate Google Vision API Using Polymer

我正在尝试 运行 在 Google Cloud Vision API 上进行测试,看看它对客户端的影响如何 Shape Detection API

我希望 POST JSON 使用 base64 编码的图像并返回图像文本和条形码。

我已经根据 (https://cloud.google.com/vision/docs/before-you-begin) 上的教程创建了一个 GCP 项目和 API 密钥,但是在尝试发出请求时出现 401 错误。

error: {code: 401,…}
code: 401
message: "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project."
status: "UNAUTHENTICATED"

请求用Polymer写2.x如下:

<iron-ajax id="googleApi" 
  body="[[request]]" 
  content-type="application/json" 
  handle-as="json"
  headers$='{"Authorization": "Bearer [[GOOGLE_API_KEY]]"}' 
  last-response="{{response}}" 
  loading="{{loading}}"
  method="post" 
  url="https://vision.googleapis.com/v1/images:annotate">
</iron-ajax>

...

GOOGLE_API_KEY: {
  type: String,
  value: 'AIza0101010110100101101010'
}

...

getRequest(image) {
  let encoded = image.toString('base64');
  this.request = {
    "requests": [{
      "image": {
        "content": encoded
      },
      "features": [{
        "type": "LABEL_DETECTION",
        "maxResults": 1
      }]
    }]
  };
  let request = this.$.googleApi.generateRequest();
  request.completes.then(req => {
    console.log('submission complete');
    console.log(this.response);
  })
  .catch(error => {
    console.log(error);
  })
}

如何解决此身份验证错误?

这是帐户管理问题?代码格式不正确?

不需要授权header,所以请求的形式应该是:

<iron-ajax id="googleApi" 
  body="[[request]]" 
  content-type="application/json" 
  handle-as="json"
  last-response="{{response}}" 
  loading="{{loading}}"
  method="post" 
  url="https://vision.googleapis.com/v1/images:annotate?key=[[GOOGLE_API_KEY]]">
</iron-ajax>