Home >Web Front-end >JS Tutorial >NodeJS access API officially supported by Google, providing background login authorization_node.js
Installation
This library is released via npm. Install googleapis and its dependencies through the following commands
$ npm install googleapis
Complete API support list https://developers.google.com/apis-explorer
Use
Example 1: Get the complete address through Google short address
var google = require('googleapis'); var urlshortener = google.urlshortener('v1'); var params = { shortUrl: 'http://goo.gl/xKbRu3' }; // get the long url of a shortened url urlshortener.url.get(params, function (err, response) { console.log('Long url is', response.longUrl); });
Example 2: Login authorization
This example integrates OAuth2 authentication, which allows you to obtain the user's access token and refresh this token to prevent session expiration.
var google = require('googleapis'); var plus = google.plus('v1'); var oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL); // Retrieve tokens via token exchange explained above or set them: oauth2Client.setCredentials({ access_token: 'ACCESS TOKEN HERE', refresh_token: 'REFRESH TOKEN HERE' }); plus.people.get({ userId: 'me', auth: oauth2Client }, function(err, response) { // handle err and response });
Complete login authorization example. https://github.com/google/google-api-nodejs-client/blob/master/examples/oauth2.js
Example 3: File upload
var fs = require('fs'); var drive = google.drive({ version: 'v2', auth: oauth2Client }); drive.files.insert({ resource: { title: 'testimage.png', mimeType: 'image/png' }, media: { mimeType: 'image/png', body: fs.createReadStream('awesome.png') // read streams are awesome! } }, callback);
Q&A?
If you have any questions, please go to Stackoverflow to ask
If you find a vulnerability, you can submit it on GitHub Issue