Hướng dẫn bắt đầu nhanh giải thích cách thiết lập và chạy một ứng dụng gọi một API Google Workspace. Hướng dẫn bắt đầu nhanh này sử dụng phương pháp xác thực đơn giản phù hợp với môi trường kiểm thử. Đối với môi trường phát hành công khai, bạn nên tìm hiểu về xác thực và uỷ quyền trước khi chọn thông tin đăng nhập để truy cập phù hợp với ứng dụng của bạn.
Tạo một ứng dụng dòng lệnh Node.js đưa ra yêu cầu đến Drive Labels API.
Mục tiêu
- Thiết lập môi trường.
- Cài đặt thư viện ứng dụng.
- Thiết lập mẫu.
- Chạy mẫu.
Điều kiện tiên quyết
- Đã cài đặt Node.js và npm.
- Một dự án trên Google Cloud.
- Tài khoản Google.
Thiết lập môi trường
Để hoàn tất hướng dẫn nhanh này, hãy thiết lập môi trường của bạn.
Bật API
Trước khi sử dụng API của Google, bạn cần bật các API đó trong một dự án Google Cloud. Bạn có thể bật một hoặc nhiều API trong một dự án Google Cloud.Trong Google Cloud Console, hãy bật Drive Labels API.
Uỷ quyền thông tin đăng nhập cho một ứng dụng máy tính
Để xác thực người dùng cuối và truy cập vào dữ liệu người dùng trong ứng dụng của mình, bạn cần tạo một hoặc nhiều Mã ứng dụng OAuth 2.0. Mã ứng dụng khách được dùng để xác định một ứng dụng duy nhất cho các máy chủ OAuth của Google. Nếu ứng dụng của bạn chạy trên nhiều nền tảng, bạn phải tạo một mã nhận dạng ứng dụng riêng cho mỗi nền tảng.- Trong bảng điều khiển Google Cloud, hãy chuyển đến phần Trình đơn > Google Auth platform > Ứng dụng.
- Nhấp vào Tạo ứng dụng.
- Nhấp vào Loại ứng dụng > Ứng dụng dành cho máy tính.
- Trong trường Name (Tên), hãy nhập tên cho thông tin đăng nhập. Tên này chỉ xuất hiện trong Google Cloud Console.
- Nhấp vào Tạo.
Thông tin xác thực mới tạo sẽ xuất hiện trong phần "Mã ứng dụng OAuth 2.0".
- Lưu tệp JSON đã tải xuống dưới dạng
credentials.json
rồi di chuyển tệp đó vào thư mục làm việc của bạn.
Cài đặt thư viện ứng dụng
Cài đặt các thư viện bằng npm:
npm install googleapis@113 @google-cloud/local-auth@2.1.1 --save
Thiết lập mẫu
Trong thư mục làm việc, hãy tạo một tệp có tên là
index.js
.Trong tệp này, hãy dán đoạn mã sau:
const fs = require('fs'); const readline = require('readline'); const {google} = require('googleapis'); // If modifying these scopes, delete token.json. const SCOPES = ['https://www.googleapis.com/auth/drive.labels.readonly']; // The file token.json stores the user's access and refresh tokens, and is // created automatically when the authorization flow completes for the first // time. const TOKEN_PATH = 'token.json'; // Load client secrets from a local file. 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 Drive Labels // API. authorize(JSON.parse(content), listDriveLabels); }); /** * 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) { const {client_secret, client_id, redirect_uris} = credentials.installed; const oAuth2Client = new google.auth.OAuth2( client_id, client_secret, redirect_uris[0]); // Check if we have previously stored a token. fs.readFile(TOKEN_PATH, (err, token) => { if (err) return getNewToken(oAuth2Client, callback); oAuth2Client.setCredentials(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 for the authorized client. */ 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 listDriveLabels(auth) { const service = google.drivelabels({version: 'v2', auth}); const params = { 'view': 'LABEL_VIEW_FULL' }; service.labels.list(params, (err, res) => { if (err) return console.error('The API returned an error: ' + err); const labels = res.data.labels; if (labels) { labels.forEach((label) => { const name = label.name; const title = label.properties.title; console.log(`${name}\t${title}`); }); } else { console.log('No Labels'); } }); }
Chạy mẫu
Trong thư mục làm việc, hãy chạy mẫu:
node .
Trong lần đầu tiên chạy mẫu, bạn sẽ được nhắc uỷ quyền truy cập:
- Nếu chưa đăng nhập vào Tài khoản Google, bạn sẽ được nhắc đăng nhập. Nếu bạn đã đăng nhập vào nhiều tài khoản, hãy chọn một tài khoản để dùng cho việc uỷ quyền.
- Nhấp vào Chấp nhận.
Thông tin uỷ quyền được lưu trữ trong hệ thống tệp, vì vậy, vào lần tiếp theo chạy mã mẫu, bạn sẽ không được nhắc uỷ quyền.
Bạn đã tạo thành công ứng dụng Node.js đầu tiên đưa ra yêu cầu đến Drive Labels API.