我用express制作了一个nodeJS应用程序。我可以从谷歌分析中检索数据,但是我无法在屏幕上显示数据,因为授权/谷歌分析API是异步的。
有人可以帮我编写一个带回调的函数,它将更新一个名为'.report'的索引页面,并在div中显示JSON。
Javascript角/ googleAuth.js
var google = require('googleapis');
var path = require("path");
var getJWTClient = {
authorize: function () {
var jwtClient = new google.auth.JWT(
'cboboekverkoperdashboardv2@clear-style-185306.iam.gserviceaccount.com',
path.join(__dirname, '../.', '/files/KEY.json'),
null,
['https://www.googleapis.com/auth/analytics.readonly'] //scope
);
jwtClient.authorize(function (err, tokens) {
console.log('jwtClient.authorize() started');
if (err) {
console.log('error in authorization:' + err);
return;
} else {
console.log('authorization success!');
var analytics = google.analytics('v3');
return queryData(analytics,jwtClient);
}
})
}
}
function queryData(analytics,jwtClient){
var VIEW_ID = 'ga:163754738';
analytics.data.ga.get({
'auth': jwtClient,
'ids': VIEW_ID,
'metrics': 'ga:uniquePageviews',
'dimensions': 'ga:pagePath',
'start-date': '30daysAgo',
'end-date': 'yesterday',
'sort': '-ga:uniquePageviews',
'max-results': 10,
}, function (err, response) {
if (err) {
console.log(err);
return;
}
console.log(JSON.stringify(response, null, 4));
// should be able to update the .report on index page with this information.
return JSON.stringify(response, null, 4);
});
}
module.exports = getJWTClient;
我的app.js
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
index.pug
extends layout
block content
h1= title
p Welcome to #{title}
div(class='report') #{jsonReport}
路由/ index.pug
var express = require('express');
var router = express.Router();
var googleAuth = require('../public/javascripts/googleAuth.js');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Dashboard', jsonReport: googleAuth.authorize() });
});
module.exports = router;