云视界API的授权承载令牌。

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

问题

我写了一个云函数,把base64字符串传到Google Cloud Vision API中,我还在客户端写了一个函数,通过HTTP调用Firebase云函数。

虽然数据很好地从客户端传递到云函数,但从服务器向Google Vision API发出的请求却无法工作。我得到的状态码是 500 错误。

我很确定这与授权承载令牌有关,因为在shell中运行这个命令时,环境变量是 GOOGLE_APPLICATION_CREDENTIALS 工作就可以了。对了,运行云函数时,同样的环境变量也存在。

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...
firebase axios google-cloud-functions bearer-token google-cloud-vision
1个回答
0
投票

最好的解决方案是使用 客户库. 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))
})
© www.soinside.com 2019 - 2024. All rights reserved.