首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >未经授权通过JavaScript访问Google Calendar API

未经授权通过JavaScript访问Google Calendar API
EN

Stack Overflow用户
提问于 2012-12-01 02:31:50
回答 1查看 23K关注 0票数 23

我正在尝试访问包含国家假日的公共日历(来自Google Calendar):

代码语言:javascript
复制
calendarId: 'pt_br.brazilian#holiday@group.v.calendar.google.com'

由于日历是公开的,我认为我可以只使用API密钥来访问它:

代码语言:javascript
复制
function OnLoadCallback() {
    var config = {
        client_id: '32j4lk32j5kj342l5h.googleuser.com', //fake client id
        scope: 'https://www.googleapis.com/auth/calendar.readonly'
    };
    gapi.client.setApiKey('fId345AM20HXXXXXXXXXXXXXXXXgT3f9kyp2REfkaw2'); //fake api key
    gapi.client.load('calendar', 'v3', function() {
        var today = new Date(),
            request;

        request = gapi.client.calendar.calendarList.get({
            calendarId: 'pt_br.brazilian#holiday@group.v.calendar.google.com',
            timeMin: (new Date(today.getFullYear(), today.getMonth(), today.getDay(), 0, 0, 0, 0)).toISOString(),
            timeMax: (new Date(today.getFullYear(), today.getMonth(), today.getDay(), 23, 59, 59, 999)).toISOString(),
            fields: 'items(creator(displayName,email),end,endTimeUnspecified,start,summary)'
        });

        request.execute(function(response) {
            window.alert('length of items: ' + response.items.length);
        });

    });
}

但是,我一直收到以下响应,这是一个401 (未授权)错误:

代码语言:javascript
复制
{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Login Required",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Login Required"
 }
}

有没有人能澄清一下我想要做的事情是不是可以实现?

最后,如果可能的话--参考我当前的代码,我必须改变什么?

EN

回答 1

Stack Overflow用户

发布于 2021-07-07 21:04:35

使用普通的javascript,我能够完成上面的工作,也能让它工作!这真的很有帮助,因为我发现Google docs主要关注用户访问和更新日历的Auth方面的事情。要真正了解我需要呼叫的确切位置(在哪个精确的端点)就更难了。我显然已经把XXXXX放在你的calendarId和API Key需要的地方了。

代码语言:javascript
复制
    //async function to handle data fetching
    async function getData () {
    //try catch block to handle promises and errors
    try {
        const calendarId = 'XXXXXXXXXXXXX@group.calendar.google.com'
        const myKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX'
        //using await and fetch together as two standard ES6 client side features to extract the data
        let apiCall = await fetch('https://www.googleapis.com/calendar/v3/calendars/' + calendarId+ '/events?key=' + myKey)
        //response.json() is a method on the Response object that lets you extract a JSON object from the response
        //response.json() returns a promise resolved to a JSON object
        let apiResponse = await apiCall.json()
        console.log(apiResponse)
    } catch (error) {
        console.log(error)
    }
}
getData()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13651017

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档