You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js调用Google Photos API访问共享相册时API初始化报错排查

问题描述

我尝试构建一个使用Node.js、服务账号凭证调用Google Photos API来检索照片或访问共享相册的简单服务,使用了如下代码:

import { google } from 'googleapis';

const SCOPES = ['https://www.googleapis.com/auth/photoslibrary.readonly'];

// Load the service account key
import key from './servicekeyoauth.json' assert { type: 'json' };

// Create an OAuth2 client
const authClient = new google.auth.JWT({
    email: key.client_email,
    key: key.private_key,
    scopes: SCOPES,
});

// Initialize the Photos Library API client
const photosLibrary = google.photoslibrary({
    version: 'v1',
    auth: authClient,
});

async function getPhotosFromSharedAlbum() {
    try {
        // Authenticate with the OAuth2 client
        await authClient.authorize();

        // Replace 'sharedAlbumId' with your shared album ID
        const sharedAlbumId = 'ALBUM_ID';

        // List the media items (photos) from the shared album
        const response = await photosLibrary.mediaItems.search({
            albumId: sharedAlbumId,
        });

        const mediaItems = response.data.mediaItems;

        // Process the media items (photos)
        console.log('Media Items:');
        mediaItems.forEach((mediaItem, index) => {
            console.log(`Photo ${index + 1}:`);
            console.log(`Title: ${mediaItem.filename}`);
            console.log(`Media URL: ${mediaItem.baseUrl}`);
        });
    } catch (error) {
        console.error('Error:', error.message);
    }
}

// Call the function to retrieve photos from the shared album
getPhotosFromSharedAlbum();

运行代码时出现错误:google.photoslibrary is not a function,将代码修改为new google.photoslibrary({...})后,又出现错误:google.photoslibrary is not a constructor,请问这是什么原因?

原因及解决方法

核心错误原因

  1. API客户端命名错误:googleapis库中Google Photos API的客户端是驼峰命名的google.photosLibrary,而非全小写的google.photoslibrary,这是导致函数/构造器不存在错误的直接原因。
  2. 服务账号的局限性:Google Photos API不支持服务账号直接访问个人Google账号的相册或共享相册。服务账号是独立的实体,没有绑定个人Photos库,且个人账号无法将相册共享给服务账号;仅当相册属于Google Workspace账号,并明确共享给服务账号邮箱时,才有可能访问。

修正后的代码

先修正客户端初始化的命名问题,同时添加权限错误提示:

import { google } from 'googleapis';

const SCOPES = ['https://www.googleapis.com/auth/photoslibrary.readonly'];

// Load the service account key
import key from './servicekeyoauth.json' assert { type: 'json' };

// Create an OAuth2 client
const authClient = new google.auth.JWT({
    email: key.client_email,
    key: key.private_key,
    scopes: SCOPES,
});

// 修正:使用正确的驼峰命名photosLibrary
const photosLibrary = google.photosLibrary({
    version: 'v1',
    auth: authClient,
});

async function getPhotosFromSharedAlbum() {
    try {
        await authClient.authorize();
        const sharedAlbumId = 'ALBUM_ID';

        const response = await photosLibrary.mediaItems.search({
            albumId: sharedAlbumId,
        });

        // 处理mediaItems为空的情况
        const mediaItems = response.data.mediaItems || [];
        console.log('Media Items:');
        mediaItems.forEach((mediaItem, index) => {
            console.log(`Photo ${index + 1}:`);
            console.log(`Title: ${mediaItem.filename}`);
            console.log(`Media URL: ${mediaItem.baseUrl}`);
        });
    } catch (error) {
        console.error('Error:', error.message);
        // 针对权限错误的提示
        if (error.response?.status === 403) {
            console.log('提示:服务账号无法访问个人Google Photos内容,若需访问个人账号资源,请改用OAuth 2.0授权码流程');
        }
    }
}

getPhotosFromSharedAlbum();

额外注意事项

  • 若要访问个人Google账号的Photos资源,必须使用OAuth 2.0授权码流程,引导用户手动授权,而非服务账号。
  • 确保googleapis库为最新版本,执行npm install googleapis@latest更新。

内容的提问来源于stack exchange,提问作者Y.D

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 05:14:52