#node.js #google-api #google-classroom
#node.js #google-api #google-classroom
Вопрос:
Я новичок в API Google и новичок в node.JS . Я не могу понять, почему создание курса не работает.
Сценарий для создания курса представляет собой модифицированную версию примера сценария приложений, доступного на веб-сайте разработчика Google.
Помощь очень ценится, поскольку я молодой студент, пытающийся создать собственную платформу электронного обучения на основе Google Classroom и других готовых решений.
Я что-то упускаю?
const readline = require('readline');
const {google} = require('googleapis');
const chalk = require('chalk');
const SCOPES = ['https://www.googleapis.com/auth/classroom.courses',
const TOKEN_PATH = 'token.json';
fs.readFile('credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Google Classroom API.
authorize(JSON.parse(content), listCourses, createCourse);
});
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);
// Store the token to disk for later program executions
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) return console.error(err);
console.log('Token stored to', TOKEN_PATH);
});
callback(oAuth2Client);
});
});
}
function listCourses(auth) {
const classroom = google.classroom({version: 'v1', auth});
classroom.courses.list({
pageSize: 1234,
}, (err, res) => {
if (err) return console.error(chalk.red('[ERROR] ') err);
const courses = res.data.courses;
if (courses amp;amp; courses.length) {
console.log('Courses:');
courses.forEach((course) => {
console.log(`${course.name} (${course.id})`);
});
} else {
console.log('No courses found.');
}
});
}
function createCourse(auth) {
const classroom = google.classroom({version: 'v1', auth});
classroom.courses.create({
name: 'somethin!',
section: 'Period 2',
descriptionHeading: 'somethin',
description: "somethin",
room: '301',
ownerId: 'me',
courseState: 'PROVISIONED',
}, (err, res) => {
if (err) return console.error(chalk.red('[ERROR] ') err);
});
}```
Ответ №1:
Можете ли вы попробовать разделить вызов listCourses и createCourse.
authorize()
принимает 2 аргумента: учетные данные и обратный вызов.
fs.readFile('credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Google Classroom API.
authorize(JSON.parse(content), listCourses);
authorize(JSON.parse(content), createCourse);
});
Я попытался создать курс, используя тело вашего запроса, и это было успешно.
courses.create
Вы также можете объединить свои listCourses()
и createCourse()
в одну функцию, чтобы вам не нужно было получать токен аутентификации для каждого запроса.
(ОБНОВЛЕНИЕ):
Можете ли вы попробовать это:
function createCourse(auth) {
const classroom = google.classroom({version: 'v1', auth});
classroom.courses.create({
resource: {
name: 'somethin!',
section: 'Period 2',
descriptionHeading: 'somethin',
description: "somethin",
room: '301',
ownerId: 'me',
courseState: 'PROVISIONED',
},
}, (err, res) => {
if (err) return console.error(chalk.red('[ERROR] ') err);
});
}
Из-за отсутствия node.js примеры в Classroom API я попытался найти другой Google API, который отправляет только тело запроса.
Я нашел этот API календаря бесплатным.запрос и на основе этого примера node.js код, он назывался так:
calendar.freebusy.query(
{
resource: {
timeMin: eventStartTime,
timeMax: eventEndTime,
timeZone: 'America/Denver',
items: [{ id: 'primary' }],
},
},
(err, res) => {
// Check for errors in our query and log them if they exist.
if (err) return console.error('Free Busy Query Error: ', err) });
тело запроса было задано в качестве параметра ресурса
Комментарии:
1. Это не сработало. Теперь я получаю эту ошибку:
Error: Invalid JSON payload received. Unknown name "room": Cannot bind query parameter. Field 'room' could not be found in request message.
для каждого параметра.2. @thicc, я обновил ответ. Можете ли вы попробовать, если это сработает. Я не могу воспроизвести вашу проблему, поскольку у меня нет необходимой среды. Я просто пытался искать возможные решения в Интернете.
3. Это сработало!! БОЛЬШОЕ ВАМ СПАСИБО!!! ТЫ ЛУЧШИЙ