如何使用google-auth-library-nodejs

时间:2019-02-27 01:02:55

标签: google-api google-oauth2 google-photos google-photos-api google-auth-library-nodejs

我尝试将照片上传到具有google-auth-library-nodejs的经过身份验证的帐户,主要是按照示例here进行。我已使用OAuth2Client成功验证了客户端,并正在首先使用图像发出发布请求,然后创建媒体项。但是,我一直从mediaItems:batchCreate POST请求中得到此错误。

media item creation status:  { code: 3,
  message:
   'NOT_IMAGE: There was an error while trying to create this media item.' }
{ expiry_date: 1551232184753,
  scopes:
   [ 'https://www.googleapis.com/auth/photoslibrary.appendonly' ],
  azp:
   '279811607028-ne3ln378urka8e6gn1nknag92uv7qhvs.apps.googleusercontent.com',
  aud:
   '279811607028-ne3ln378urka8e6gn1nknag92uv7qhvs.apps.googleusercontent.com',
  exp: '1551232184',
  access_type: 'offline' }

我怀疑这是因为Oauth2Client.request中的Gaxios对象参数在base64中编码了请求的数据,而photos api文档要求了二进制数据。有没有办法在Gaxios对象中覆盖此行为?我可以发出普通的发帖请求,但我想保留google-auth-library的好处。这是我的代码。

const oAuth2Client = await getAuthenticatedClient();

let image = fs.readFileSync(path.join(__dirname, '../diagrams/camera_mod_measurements.jpg') );

// Make a simple request to the People API using our pre-authenticated client. The `request()` method
// takes an GaxiosOptions object.  Visit https://github.com/JustinBeckwith/gaxios.
const requestParams = {
    url: "https://photoslibrary.googleapis.com/v1/uploads",
    method: "POST",
    headers: {
        "Content-Type": "application/octet-stream",
        "X-Goog-Upload-File-Name": "test1",
        "X-Goog-Upload-Protocol": "raw"
    },
    data: {
        MEDIA_BINARY_DATA: image
    },
    params: {

    },
}
const uploadToken = await oAuth2Client.request(requestParams);
console.log("UPLOAD TOKEN:", uploadToken.data);

const mediaItemRequest = {
    url: "https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate",
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    data: {
        "newMediaItems": [
            {
                "description": "TEST",
                "simpleMediaItem": {
                    "uploadToken": uploadToken.data
                }
            }
        ]
    }
};

const mediaItemResponse = await oAuth2Client.request(mediaItemRequest);
console.log(mediaItemResponse.data);
console.log("media item creation status: ", mediaItemResponse.data.newMediaItemResults[0].status);

谢谢!

0 个答案:

没有答案