问题描述
我有一个Web应用程序,通过它我可以创建播放列表,将视频添加到播放列表,删除视频等到我的YouTube频道。我已经创建了一个服务帐户,并下载了该服务帐户凭据密钥文件,并在Google Developer Console中设置了我的OAuth 2.0客户端ID。 为了对我的应用进行身份验证,我在{strong>服务帐户凭据
下,按照https://github.com/googleapis/google-api-nodejs-clientREADME.md
此处TypeError: Cannot read property 'redirect_uris' of undefined的说明进行操作
这是我的控制器文件...
我应该注意,该项目使用ES模块,因此google-api-nodejs-client
设置为"type": "module"
。例如,这就是为什么您会注意到我将package.json
导入为实用程序,因为ES模块不支持常规的__dirname
。
__dirname
import googleapi from "googleapis";
const { google } = googleapi;
import Auth from "@google-cloud/local-auth";
const { authenticate } = Auth;
import path from "path";
import __dirname from "../utils/dirname.js";
async function initialize() {
try {
const auth = await authenticate({
keyfilePath: path.join(__dirname,"../service_account_credentials.json"),scopes: ["https://www.googleapis.com/auth/youtube"],});
console.log("Auth details");
console.log(auth);
google.options({ auth });
} catch (e) {
console.log(e);
}
}
initialize();
const oauth2client = new google.auth.OAuth2(
"YOUR_CLIENT_ID","YOUR_CLIENT_SECRET","http://localhost:5000/oauth2callback"
);
// initialize the Youtube API library
const youtube = google.youtube({ version: "v3",auth: oauth2client });
class YoutubeController {
static async createPlaylist(req,res) {
const { name } = req.body;
const playlist = await youtube.playlists.insert({
part: "snippet,status",resource: {
snippet: {
title: name,description: `${name} videos.`,},status: {
privacyStatus: "private",});
res.json(playlist);
}
}
函数是引发错误的函数,我不太清楚。我认为因此,当我向类中调用方法initialize
的路由发出POST
请求时,我得到了createPlaylist
我一直在浏览文档,试图了解一切如何进行,但是我有点卡住了。
此处提出了类似的问题-{{3}},但没有答案,建议的工作流程不适用于我的情况,因此,非常感谢您的帮助。
解决方法
服务帐户
YouTube API不支持您需要使用OAuth2进行的服务帐户身份验证。
OAuth2授权
您可能要考虑遵循YouTube API quick start for nodejs.
问题是您正在使用不支持的YouTube API使用服务帐户身份验证。
var fs = require('fs');
var readline = require('readline');
var {google} = require('googleapis');
var OAuth2 = google.auth.OAuth2;
// If modifying these scopes,delete your previously saved credentials
// at ~/.credentials/youtube-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/youtube.readonly'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'youtube-nodejs-quickstart.json';
// Load client secrets from a local file.
fs.readFile('client_secret.json',function processClientSecrets(err,content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials,then call the YouTube API.
authorize(JSON.parse(content),getChannel);
});
/**
* Create an OAuth2 client with the given credentials,and then execute the
* given callback function.
*
* @param {Object} credentials The authorization client credentials.
* @param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials,callback) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var oauth2Client = new OAuth2(clientId,clientSecret,redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH,function(err,token) {
if (err) {
getNewToken(oauth2Client,callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
}
/**
* Get and store new token after prompting for user authorization,and then
* execute the given callback with the authorized OAuth2 client.
*
* @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
* @param {getEventsCallback} callback The callback to call with the authorized
* client.
*/
function getNewToken(oauth2Client,callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',scope: SCOPES
});
console.log('Authorize this app by visiting this url: ',authUrl);
var rl = readline.createInterface({
input: process.stdin,output: process.stdout
});
rl.question('Enter the code from that page here: ',function(code) {
rl.close();
oauth2Client.getToken(code,token) {
if (err) {
console.log('Error while trying to retrieve access token',err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
}
/**
* Store token to disk be used in later program executions.
*
* @param {Object} token The token to store to disk.
*/
function storeToken(token) {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code != 'EEXIST') {
throw err;
}
}
fs.writeFile(TOKEN_PATH,JSON.stringify(token),(err) => {
if (err) throw err;
console.log('Token stored to ' + TOKEN_PATH);
});
}
/**
* Lists the names and IDs of up to 10 files.
*
* @param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function getChannel(auth) {
var service = google.youtube('v3');
service.channels.list({
auth: auth,part: 'snippet,contentDetails,statistics',forUsername: 'GoogleDevelopers'
},response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
var channels = response.data.items;
if (channels.length == 0) {
console.log('No channel found.');
} else {
console.log('This channel\'s ID is %s. Its title is \'%s\',and ' +
'it has %s views.',channels[0].id,channels[0].snippet.title,channels[0].statistics.viewCount);
}
});
}
从YouTube API quick start for nodejs.中无耻地撕掉代码
后端访问
由于YouTube API不支持服务帐户。从后端服务访问数据可能很棘手,但这不是不可能的。
- 在本地运行一次应用程序。
- 自动刷新以访问您的帐户数据。
- 在您的代码中找到存储的凭据,其中应包含刷新令牌。
- 将此刷新令牌保存为应用程序的一部分。
- 设置代码以在加载时读取此刷新令牌。
不幸的是,我不是node.js开发人员,所以我不能为您提供执行此操作所需的代码。如果您可以找到该库并将其装入,则该库应该将内容存储到凭据对象中。那么您应该能够执行我建议的操作。
我将从深入研究storeToken(token);
所做的事情开始。