Cloud Vision API的授权承载令牌

时间:2020-06-05 00:33:25

标签: firebase axios google-cloud-functions bearer-token google-cloud-vision

问题

我编写了一个包含base64字符串并将其传递到Google Cloud Vision API的云函数,并且还在客户端上编写了一个通过HTTP调用Firebase Cloud Function的函数。

尽管数据可以很好地从客户端传递到Cloud Function,但是服务器对Google Vision API的请求无法正常工作。我收到状态代码500错误。

我非常确定这与Authorization承载令牌有关,因为在环境变量GOOGLE_APPLICATION_CREDENTIALS的shell中运行此令牌可以正常工作。顺便说一句,运行云功能时存在相同的环境变量。

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://vision.googleapis.com/v1/images:annotate

我是否使用了正确的承载令牌(请参见下面的代码)?我如何才能使该请求通过?

客户端

auth.currentUser.getIdToken()
        .then((idToken) => {
          axios({
            method: 'post',
            url: 'http://localhost:5001/project/my-endpoint',
            data: qs.stringify({
              imageData: image,
              token: idToken
            }),
            maxContentLength: 100000,
            maxBodyLength: 100000
          }) // .then, .catch follows...
        })

服务器端

axios({
        method: 'post',
        url: 'https://vision.googleapis.com/v1/images:annotate',
        headers: {
            "Authorization": `Bearer ${request.body.token}`,
            "Content-Type": "application/json; charset=utf-8"
        },
        data: {
            "requests": [
                {
                    "image": {
                        "content": request.body.imageData   
                    },
                    "features": [
                        {
                            "type": "DOCUMENT_TEXT_DETECTION"
                        }
                    ]
                }
            ]
        },
        maxContentLength: 100000,
        maxBodyLength: 100000
    }) // .then, .catch follows...

1 个答案:

答案 0 :(得分:0)

最好的解决方案是使用client library。 Google页面上的文档虽然不是很好,但是这些文档要好得多。

代码应如下所示:

const vision = require('@google-cloud/vision')
const client = new vision.ImageAnnotatorClient()

const fileName = request.body.imageData // base64 image data

    const req = {
        image: {
            content: fileName
        }
    }

    client.documentTextDetection(req)
        .then(result => response.send(result))
        .catch(error => response.send(error))
})