В запросе Google Slides API Node.Js неверные учетные данные для аутентификации - PullRequest
0 голосов
/ 30 октября 2018

Я получаю эту ошибку:

Expected OAuth 2 access token, login cookie or other valid authentication credential

всякий раз, когда я запускаю свою программу. Вот мой код.

const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
const promise = require('promise');
const slides = google.slides({
    version: 'v1',
    auth: 'CLIENT_SECRET'
});
const SCOPES = ['https://www.googleapis.com/auth/presentations', 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/drive.appdata', 'https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email'];
const TOKEN_PATH = 'token.json';

fs.readFile('credentials.json', (err, content) => {
    if (err) return console.log('Error loading client secret file:', err);
    authorize(JSON.parse(content), createSlide);
});

function authorize(credentials, callback) {
    const {client_secret, client_id, redirect_uris} = credentials.installed;
    const oAuth2Client = new google.auth.OAuth2(
        client_id, client_secret, redirect_uris[0]
    );
    fs.readFile(TOKEN_PATH, (err, token) => {
        if (err) return getNewToken(oAuth2Client, callback);
        oAuth2Client.setCredentials(JSON.parse(token));
        callback(oAuth2Client);
    });
}

function getNewToken(oAuth2Client, callback) {
    const authUrl = oAuth2Client.generateAuthUrl({
        access_type: 'offline',
        scope: SCOPES,
    });
    console.log('Authorize this app by visiting this url:', authUrl);
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
    });
    rl.question('Enter the code from that page here: ', (code) => {
        rl.close();
        oAuth2Client.getToken(code, (err, token) => {
            if (err) return console.error('Error retrieving access token', err);
            oAuth2Client.setCredentials(token);
            fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
                if (err) console.error(err);
                console.log('Token stored to', TOKEN_PATH);
            });
            callback(oAuth2Client);
        });
    });
}

function createSlide(presentationId, pageId, auth) {
    return new Promise((resolve, reject) => {
        let requests = [{
            createSlide: {
                objectId: pageId,
                insertionIndex: '1',
                slideLayoutReference: {
                    predefinedLayout: 'TITLE_AND_TWO_COLUMNS',
                },
            },
        }];

        //ELEMENTS

        slides.presentations.batchUpdate({
            presentationId,
            resource: {
                requests,
            },
            }, (err, res) => {
                if (err) return console.log("Error: " + err);
                console.log(`Created slide with ID: ${res.replies[0].createSlide.objectId}`);
                resolve(res);
        });
    });
}

Код взят из быстрого запуска node.js (https://developers.google.com/slides/quickstart/nodejs).

Функция createSlide () взята из фрагментов Github Node.Js (https://github.com/gsuitedevs/node-samples/blob/master/slides/snippets/snippets.js#L78)

).

Я пробовал код на Github для клиента API Google Node.js (https://github.com/googleapis/google-api-nodejs-client)

Я довольно новичок в Google API и Node.Js, поэтому я все еще изучаю асинхронность и обещание. Может кто-нибудь сказать мне, что я делаю неправильно, и, возможно, привести полный рабочий пример (не фрагменты)? Заранее спасибо!

...