我尝试验证连接到Google API以使用Google Analytics。这是我的代码:
'use strict'
const fs = require('fs')
const open = require('open')
const Fs = require('fs')
const Google = require('googleapis')
const Url = require('url')
const Http = require('http')
const CREDENTIALS_DIR = './.credentials/'
const SECRET_PATH = CREDENTIALS_DIR + 'google-analytics-secret.json'
const TOKEN_PATH = CREDENTIALS_DIR + 'google-analytics-accesstoken.json'
let auth = loadCredentials()
const oauth2Client = new Google.auth.OAuth2(
auth.CLIENT_ID,
auth.CLIENT_SECRET,
auth.REDIRECT_URL)
function loadCredentials () {
try {
let secret = Fs.readFileSync(SECRET_PATH)
console.log('Credentials successfully loaded from file.')
return {
CLIENT_ID: JSON.parse(secret).web.client_id,
CLIENT_SECRET: JSON.parse(secret).web.client_secret,
REDIRECT_URL: JSON.parse(secret).web.redirect_uris[0]
}
}
catch (err) {
if (err.code !== 'ENOENT') {
throw err
}
else {
console.log('Credentials successfully loaded from environment.')
return {
CLIENT_ID: process.env.GOOGLE_CLIENT_ID,
CLIENT_SECRET: process.env.GOOGLE_CLIENT_SECRET,
REDIRECT_URL: 'http://localhost:1234/'
}
}
}
}
function getScopes () {
return [
'https://www.googleapis.com/auth/drive.readonly',
'https://www.googleapis.com/auth/analytics.readonly'
]
}
function getAuthCallbackServer () {
let url = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: getScopes()
})
open(url, 'chrome')
let server = Http.createServer(handleAuthCallback)
server.listen(9999, () => {
console.log('Server listening on: http://localhost:1234')
})
}
// Parse Code sent by Google
function handleAuthCallback (req, res) {
let parse = Url.parse(req.url)
let code = parse.query.split('=').pop()
console.log(`Got code: ${code}`)
res.writeHead(200)
res.end('Awesome... Got the Code')
}
getAuthCallbackServer()
我尝试使用函数使其模块化,并且我得到以下错误(在handleAuthCallback函数内):
TypeError: Cannot read property 'split' of null
这是我尝试在handleAuthCallback函数中打印parse
时得到的对象:
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: '?code=x/xxxxxxxxxxxxxxxxxxxxxxxx',
query: 'code=x/xxxxxxxxxxxxxxxxxxxxxxxx',
pathname: '/',
path: '/?code=x/xxxxxxxxxxxxxxxxxxxxxxxx',
href: '/?code=x/xxxxxxxxxxxxxxxxxxxxxxxx' }
在重构我的代码之前,我并没有真正理解这个错误。关于我可能出错的地方的任何建议?
感谢。
答案 0 :(得分:0)
正在调用此function
:
// Parse Code sent by Google
function handleAuthCallback (req, res) {
let parse = Url.parse(req.url)
let code = parse.query.split('=').pop()
console.log(`Got code: ${code}`)
res.writeHead(200)
res.end('Awesome... Got the Code')
}
在此处指定回调时:
let server = Http.createServer(handleAuthCallback)
Url
在此处定义:
const Url = require('url')
解析是Url.parse(req.url)
的结果。这没有查询属性,因此parse.query
为undefined
,因此parse.query.split
会产生错误,当您进行一些重构时,可能会定义query
的代码被删除了。
答案 1 :(得分:0)
假设query
是对象,请尝试:
let parse = Url.parse(req.url);
let code = parse.query.code;