Node.js TypeError:无法读取属性';重定向URI';未定义的Youtube数据API身份验证节点数
我有一个web应用程序,通过它我可以创建播放列表,将视频添加到播放列表,删除视频,等等,添加到我的youtube频道。我已经创建了一个服务帐户,下载了服务帐户凭据密钥文件,并在Google开发者控制台中设置了OAuth 2.0客户端ID。 为了验证我的应用程序,我按照Node.js TypeError:无法读取属性';重定向URI';未定义的Youtube数据API身份验证节点数,node.js,google-api,google-oauth,youtube-data-api,google-api-nodejs-client,Node.js,Google Api,Google Oauth,Youtube Data Api,Google Api Nodejs Client,我有一个web应用程序,通过它我可以创建播放列表,将视频添加到播放列表,删除视频,等等,添加到我的youtube频道。我已经创建了一个服务帐户,下载了服务帐户凭据密钥文件,并在Google开发者控制台中设置了OAuth 2.0客户端ID。 为了验证我的应用程序,我按照README.md中关于google api nodejs客户端的说明进行了操作-在服务帐户凭据下 这是我的控制器文件。。。 我应该注意,该项目使用ES模块,因此“type”:“module”是在package.json中设置的。这
README.md
中关于google api nodejs客户端的说明进行了操作-在服务帐户凭据下
这是我的控制器文件。。。
我应该注意,该项目使用ES模块,因此“type”:“module”
是在package.json
中设置的。这就是为什么您会注意到,例如,我正在将\uuuu dirname
作为实用程序导入,因为ES模块不支持常规的\uuu 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
函数是抛出错误的函数,我不能完全理解它。因此,当我向类内调用方法createPlaylist
的路由发出POST
请求时,我返回未设置访问、刷新令牌或API密钥。
我一直在浏览文档,试图了解一切是如何进行的,但我有点卡住了
这里有人问了一个类似的问题,但没有答案,而且建议的工作流程不适用于我的案例,因此我非常感谢您在这方面的帮助。服务帐户
YouTube API不支持使用OAuth2所需的服务帐户身份验证
OAuth2授权
<>你可能想考虑一下
问题在于,您正在使用YouTube API的服务帐户身份验证,而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, function(err, 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'
}, function(err, 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不支持服务帐户。从后端服务访问数据可能很棘手,但并非不可能
在本地运行应用程序一次
使用它访问您的帐户数据
在代码中查找存储的凭据,这些凭据应包含刷新令牌
将此刷新令牌保存为应用程序的一部分
设置代码以在加载时读取此刷新令牌
不幸的是,我不是node.js开发人员,因此我无法帮助您完成这项工作所需的代码。库应该将内容存储到凭证对象中,如果您可以找到凭证对象以及如何加载凭证对象,那么您应该能够按照我的建议进行操作
首先,我要深入研究一下什么是storeToken(token)
正在运行。因此,没有办法避免导航到其他URL进行身份验证吗?我想也许可以在后端静默地进行身份验证,然后将视频发布到我的频道。Oauth2不要求用户出示同意书,以便同意访问您的应用程序。您可以只需存储刷新令牌并在backed中使用该刷新令牌,然后您就可以根据需要访问帐户。access_type:“offline”为您提供所需的刷新令牌。我的用例有点奇怪。与在其他地方存储一些视频文件不同,我想也许可以将它们上传到我的youtube频道,然后拉到我的网站上。使用Oauth2,这意味着每次我从不同的计算机打开站点时都必须对自己进行身份验证,其他人不能代表我上传。因此,我的用例似乎是不可能的,所以我猜谷歌云存储会这样做吗?事实上,使用我的解决方案,您只需在后端运行一个带有存储刷新令牌的脚本即可访问您的帐户。假设您将它们公开上传到您的频道,那么您应该能够在您的站点上显示它们。很抱歉,我无法帮助您使用云存储,但我认为这将是一个非常昂贵的选择。刚刚在后端访问上看到您的编辑。我试试看。如果我弄明白了,我会把代码放在这里。谢谢你,伙计。