在 Chrome 扩展程序中使用 Google Calendar API 获取日历列表时出现 403 错误

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

我正在开发一个与 Google Calendar API 交互的 Chrome 扩展程序。我已经成功实现了一个获取当前和即将发生的事件的函数,但在尝试使用类似的函数获取日历列表时遇到了 403 错误。

这是获取事件的工作函数:

enter code herefunction fetchCurrentAndUpcomingEvents(token) {
const now = new Date();
const oneHourLater = new Date(now.getTime() + (60 * 60 * 1000)); // One hour from now
const timeMin = now.toISOString();
const timeMax = oneHourLater.toISOString();

const endpoint = `https://www.googleapis.com/calendar/v3/calendars/primary/events?timeMin=${encodeURIComponent(timeMin)}&timeMax=${encodeURIComponent(timeMax)}&singleEvents=true&orderBy=startTime`;

return new Promise((resolve, reject) => {
    fetch(endpoint, {
        headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        const events = data.items;
        const currentEvents = [];
        const upcomingEvents = [];

        if (data && data.items) {
            const events = data.items; 
            events.forEach(event => {
                const eventStart = new Date(event.start.dateTime || event.start.date);
                if (eventStart <= now) {
                    currentEvents.push(event);
                } else {
                    upcomingEvents.push(event);
                }
            });
        }

        resolve({ currentEvents, upcomingEvents });
    })
    .catch(error => {
        reject(error);
    });
});
}

这是在获取日历时给我一个 403 错误的函数:

function fetchCalendars(token) {
const endpoint = 'https://www.googleapis.com/calendar/v3/users/me/calendarList';
console.log("Endpoint:", endpoint, "Token:", token); // Log the endpoint and token
return new Promise((resolve, reject) => {
    console.log("Fetching calendars with token:", token, "Endpoint:", endpoint);
    fetch(endpoint, {
        headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
        }
    })
    .then(response => {
        console.log('Response Status:', response.status); // Log the response status
        if (!response.ok) {
            throw new Error('Failed to fetch calendar list');
        }
        return response.json(); // Parse the JSON body of the response
    })
    .then(data => {
        console.log('Fetched calendars:', data.items); // Log the fetched calendar data
        resolve(data.items); // Resolve the promise with the calendar data
    })
    .catch(error => {
        console.error('Error fetching calendar list:', error);
        if (error.response) {
            console.error('Error response:', error.response);
        }
        reject(error);
    });
});
}

这两个函数都使用相同的 OAuth 令牌,我已验证该令牌具有适当的日历访问范围。 fetchCurrentAndUpcomingEvents 函数运行正常,表明令牌和请求设置正确。但是,fetchCalendars 函数失败并出现 403 错误。

我已确认我的 Google Cloud Console 中启用了 Google Calendar API,范围已正确设置为包含日历访问权限,并且我的 OAuth 同意屏幕已正确配置。

这是我在控制台中看到的错误:

Fetching calendars with token: [TOKEN] Endpoint: https://www.googleapis.com/calendar/v3/users/me/calendarList
Response Status: 403 
Error fetching calendar list: Error: Failed to fetch calendar list

我不确定为什么我能够获取事件,但无法获取具有相同标记的日历列表。任何见解或建议将不胜感激。

javascript google-chrome-extension oauth-2.0 google-calendar-api http-status-code-403
1个回答
0
投票

我找到答案了

我没有在 backgound.js 文件中设置范围,而是在 Manifest 中设置。修复此问题后,我已成功获取日历列表

© www.soinside.com 2019 - 2024. All rights reserved.