【问题标题】:TypeError: Cannot read property 'split' of nullTypeError:无法读取 null 的属性“拆分”
【发布时间】:2022-01-19 14:06:00
【问题描述】:

我尝试进行身份验证以连接到 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' }

我并不真正理解这个错误,因为它在我重构我的代码之前就起作用了。关于我可能错在哪里的任何建议?

谢谢。

【问题讨论】:

  • 您是否尝试打印parseparse.query 以验证它确实是null,然后从那里修复它?也许req.url 不是您所期望的(并且没有查询)?
  • 我认为 parse 是代码行 let code = parse.query.split('=').pop() 是一个字符串,因此它没有 query 属性。那你检查了吗?
  • 是的。 “查询”键包含代码,它在我收到错误之前使用“Got Code: ${code}”行打印代码
  • 对不起,如果它在你得到错误之前打印代码,那么可能你在另一行有错误,请检查它。因为您的控制台在出错后无法打印。
  • 脚本打印Credentials successfully loaded from file., Created auth URL., Server listening on: http://localhost:1234/, Got code: x/xxxxxxxxxxxxxxxxxxxxxxxxx 然后给我一个错误TypeError: Cannot read property 'split' of null

标签: javascript node.js typeerror


【解决方案1】:

正在调用此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.queryundefined,因此parse.query.split 会产生错误,有可能当你进行一些重构时,定义query 的代码被删除了。

【讨论】:

  • 就在let parse = Url.parse(req.url) 之后我添加了console.log(parse.query.split('=').pop()) 而不是let code = parse.query.split('=').pop() 和console.log 显示代码。它还显示带有console.log('Got code: ${code}') 的代码,但在之后给我一个错误
【解决方案2】:

假设query 是对象,试试这个:

let parse = Url.parse(req.url);
let code = parse.query.code;

【讨论】:

  • 这是我打印parse时得到的对象,它等于Url.parse(req.url)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' }
猜你喜欢
  • 2020-01-29
  • 2022-01-18
  • 1970-01-01
  • 2022-01-12
  • 2021-12-04
  • 2021-12-17
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多