Как распечатать ответ консоли почтальону или браузеру? - PullRequest
0 голосов
/ 19 июня 2020

Хорошо, я пробую использовать API Gmail? Это сводит меня с ума, я тоже в этом новичок. Прежде всего я хочу напечатать JSON ответ электронной почты и ярлыков браузеру или почтальону. Во-вторых. Каждый раз, когда я вызываю API, мне нужно повторно пройти аутентификацию.

любая помощь будет действительно принята. что я могу сделать, чтобы получить ответ на печать в браузере, который я получаю в консоли.

const { google } = require('googleapis');
const express = require('express');
const OAuth2Data = require('./credentials.json');
const fs = require('fs');
const { response } = require('express');

const app = express()
const TOKEN_PATH = 'token.json';
const CLIENT_ID = OAuth2Data.client.id;
const CLIENT_SECRET = OAuth2Data.client.secret;
const REDIRECT_URL = OAuth2Data.client.redirect_uris;

const oAuth2Client = new google.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL)
var authed = false;



app.get('/', (req, res) => {
    if (!authed) {
        // Generate an OAuth URL and redirect there
        const url = oAuth2Client.generateAuthUrl({
            access_type: 'offline',
            scope: 'https://mail.google.com/'
        });
        console.log(url)
        res.redirect(url);
    } else {
        const gmail = google.gmail({ version: 'v1', auth: oAuth2Client });
        gmail.users.labels.list({
            userId: 'me',
        }, (err, res) => {
            if (err) return console.log('The API returned an error: ' + err);
            const labels = res.data.labels;
            if (labels.length) {
                console.log('Labels:');
                labels.forEach((label) => {
                    console.log(`- ${label.name}`);
                });
            } else {
                console.log('No labels found.');
            }
        });
        res.send('Logged in')
    }
})



app.get('/auth/google/callback', function (req, res) {
    const code = req.query.code
    if (code) {
        // Get an access token based on our OAuth code
        oAuth2Client.getToken(code, function (err, token) {
            if (err) {
                console.log('Error authenticating')
                console.log(err);
            } else {
                console.log('Successfully authenticated');
                oAuth2Client.setCredentials(token);
                fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
                    if (err) return console.error(err);
                    console.log('Token stored to', TOKEN_PATH);
                  });
                authed = true;
                res.redirect('/')
            }
        });
    }
});



const port = process.env.port || 5000
app.listen(port, () => console.log(`Server running at ${port}`));


app.get('/m',(req, res) => {

    if (!authed) {
        // Generate an OAuth URL and redirect there
        const url = oAuth2Client.generateAuthUrl({
            access_type: 'offline',
            scope: 'https://mail.google.com/'
        });
        console.log(url)
        res.redirect(url);
    } 

    else {
        const gmail1 = google.gmail({ version: 'v1', auth: oAuth2Client });
        gmail1.users.messages.list({userId: 'me', maxResults: 2}, function (err, res) {
            if (err) {
                console.log('The API returned an error 1: ' + err);
                return;
            }
          // Get the message id which we will need to retreive tha actual message next.
          for (let index = 0; index < 2; index++) {
            var message_id = res['data']['messages'][index]['id'];
            gmail1.users.messages.get({auth:oAuth2Client, userId: 'me', 'id': message_id}, function(err, res) {
              if (err) {
                  console.log('The API returned an error: ' + err);
                  return;
              }

             console.log('data',res['data']);

          });

        } 
          // Retreive the actual message using the message id  
        });
    }
}) 
...