weixin_39915171
weixin_39915171
2020-11-27 12:39

While updating a row giving Google API error

Hi ,

When Iam updating a row values in the google sheet, sometimes it gives below error:


Caught error while updating status in production report>>> { Error: Google API error - [401] Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
    at createError (E:\Pippin_Projects\titles-server\node_modules\axios\lib\core\createError.js:16:15)
    at settle (E:\Pippin_Projects\titles-server\node_modules\axios\lib\core\settle.js:17:12)
    at IncomingMessage.handleStreamEnd (E:\Pippin_Projects\titles-server\node_modules\axios\lib\adapters\http.js:236:11)
    at IncomingMessage.emit (events.js:194:15)
    at IncomingMessage.EventEmitter.emit (domain.js:441:20)
    at endReadableNT (_stream_readable.js:1103:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)
  config:
   { url: '/',
     method: 'get',
     params: {},
     headers:
      { Accept: 'application/json, text/plain, */*',
        Authorization: 'Bearer undefined',
        'User-Agent': 'axios/0.19.2' },
     baseURL:
      'https://sheets.googleapis.com/v4/spreadsheets/1glk-vpeAsxeVn6wyhFcakXK-u1Ew03okfrey7bIlMsI',
     transformRequest: [ [Function: transformRequest] ],
     transformResponse: [ [Function: transformResponse] ],
     timeout: 0,
     adapter: [Function: httpAdapter],
     xsrfCookieName: 'XSRF-TOKEN',
     xsrfHeaderName: 'X-XSRF-TOKEN',
     maxContentLength: -1,
     validateStatus: [Function: validateStatus],
     data: undefined },
  request:
   ClientRequest {
     domain: null,
     _events:
      [Object: null prototype] {
        socket: [Function],
        abort: [Function],
        aborted: [Function],
        error: [Function],
        timeout: [Function],
        prefinish: [Function: requestOnPrefinish] },
     _eventsCount: 6,
     _maxListeners: undefined,
     output: [],
     outputEncodings: [],
     outputCallbacks: [],
     outputSize: 0,
     writable: true,
     _last: true,
     chunkedEncoding: false,
     shouldKeepAlive: false,
     useChunkedEncodingByDefault: false,
     sendDate: false,
     _removedConnection: false,
     _removedContLen: false,
     _removedTE: false,
     _contentLength: 0,
     _hasBody: true,
     _trailer: '',
     finished: true,
     _headerSent: true,
     socket:
      TLSSocket {
        _tlsOptions: [Object],
        _secureEstablished: true,
        _securePending: false,
        _newSessionPending: false,
        _controlReleased: true,
        _SNICallback: null,
        servername: 'sheets.googleapis.com',
        alpnProtocol: false,
        authorized: true,
        authorizationError: null,
        encrypted: true,
        _events: [Object],
        _eventsCount: 8,
        connecting: false,
        _hadError: false,
        _handle: null,
        _parent: null,
        _host: 'sheets.googleapis.com',
        _readableState: [ReadableState],
        readable: false,
        domain: null,
        _maxListeners: undefined,
        _writableState: [WritableState],
        writable: false,
        allowHalfOpen: false,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: undefined,
        _server: null,
        ssl: null,
        _requestCert: true,
        _rejectUnauthorized: true,
        parser: null,
        _httpMessage: [Circular],
        write: [Function: writeAfterFIN],
        [Symbol(res)]: [TLSWrap],
        [Symbol(asyncId)]: 18730,
        [Symbol(lastWriteQueueSize)]: 0,
        [Symbol(timeout)]: null,
        [Symbol(kBytesRead)]: 864,
        [Symbol(kBytesWritten)]: 229,
        [Symbol(connect-options)]: [Object] },
     connection:
      TLSSocket {
        _tlsOptions: [Object],
        _secureEstablished: true,
        _securePending: false,
        _newSessionPending: false,
        _controlReleased: true,
        _SNICallback: null,
        servername: 'sheets.googleapis.com',
        alpnProtocol: false,
        authorized: true,
        authorizationError: null,
        encrypted: true,
        _events: [Object],
        _eventsCount: 8,
        connecting: false,
        _hadError: false,
        _handle: null,
        _parent: null,
        _host: 'sheets.googleapis.com',
        _readableState: [ReadableState],
        readable: false,
        domain: null,
        _maxListeners: undefined,
        _writableState: [WritableState],
        writable: false,
        allowHalfOpen: false,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: undefined,
        _server: null,
        ssl: null,
        _requestCert: true,
        _rejectUnauthorized: true,
        parser: null,
        _httpMessage: [Circular],
        write: [Function: writeAfterFIN],
        [Symbol(res)]: [TLSWrap],
        [Symbol(asyncId)]: 18730,
        [Symbol(lastWriteQueueSize)]: 0,
        [Symbol(timeout)]: null,
        [Symbol(kBytesRead)]: 864,
        [Symbol(kBytesWritten)]: 229,
        [Symbol(connect-options)]: [Object] },
     _header:
      'GET /v4/spreadsheets/1glk-vpeAsxeVn6wyhFcakXK-u1Ew03okfrey7bIlMsI/ HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nAuthorization: Bearer undefined\r\nUser-Agent: axios/0.19.2\r\nHost: sheets.googleapis.com\r\nConnection: close\r\n\r\n',
     _onPendingData: [Function: noopPendingOutput],
     agent:
      Agent {
        _events: [Object],
        _eventsCount: 1,
        _maxListeners: undefined,
        defaultPort: 443,
        protocol: 'https:',
        options: [Object],
        requests: {},
        sockets: [Object],
        freeSockets: {},
        keepAliveMsecs: 1000,
        keepAlive: false,
        maxSockets: Infinity,
        maxFreeSockets: 256,
        maxCachedSessions: 100,
        _sessionCache: [Object] },
     socketPath: undefined,
     timeout: undefined,
     method: 'GET',
     path:
      '/v4/spreadsheets/1glk-vpeAsxeVn6wyhFcakXK-u1Ew03okfrey7bIlMsI/',
     _ended: true,
     res:
      IncomingMessage {
        _readableState: [ReadableState],
        readable: false,
        domain: null,
        _events: [Object],
        _eventsCount: 3,
        _maxListeners: undefined,
        socket: [TLSSocket],
        connection: [TLSSocket],
        httpVersionMajor: 1,
        httpVersionMinor: 1,
        httpVersion: '1.1',
        complete: true,
        headers: [Object],
        rawHeaders: [Array],
        trailers: {},
        rawTrailers: [],
        aborted: false,
        upgrade: false,
        url: '',
        method: null,
        statusCode: 401,
        statusMessage: 'Unauthorized',
        client: [TLSSocket],
        _consuming: true,
        _dumped: false,
        req: [Circular],
        responseUrl:
         'https://sheets.googleapis.com/v4/spreadsheets/1glk-vpeAsxeVn6wyhFcakXK-u1Ew03okfrey7bIlMsI/',
        redirects: [] },
     aborted: undefined,
     timeoutCb: null,
     upgradeOrConnect: false,
     parser: null,
     maxHeadersCount: null,
     _redirectable:
      Writable {
        _writableState: [WritableState],
        writable: true,
        domain: null,
        _events: [Object],
        _eventsCount: 2,
        _maxListeners: undefined,
        _options: [Object],
        _redirectCount: 0,
        _redirects: [],
        _requestBodyLength: 0,
        _requestBodyBuffers: [],
        _onNativeResponse: [Function],
        _currentRequest: [Circular],
        _currentUrl:
         'https://sheets.googleapis.com/v4/spreadsheets/1glk-vpeAsxeVn6wyhFcakXK-u1Ew03okfrey7bIlMsI/' },
     [Symbol(isCorked)]: false,
     [Symbol(outHeadersKey)]:
      [Object: null prototype] {
        accept: [Array],
        authorization: [Array],
        'user-agent': [Array],
        host: [Array] } },
  response:
   { status: 401,
     statusText: 'Unauthorized',
     headers:
      { 'www-authenticate':
         'Bearer realm="https://accounts.google.com/", error="invalid_token"',
        vary: 'X-Origin, Referer, Origin,Accept-Encoding',
        'content-type': 'application/json; charset=UTF-8',
        date: 'Tue, 25 Feb 2020 09:42:18 GMT',
        server: 'ESF',
        'cache-control': 'private',
        'x-xss-protection': '0',
        'x-frame-options': 'SAMEORIGIN',
        'alt-svc':
         'quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000',
        'accept-ranges': 'none',
        connection: 'close' },
     config:
      { url: '/',
        method: 'get',
        params: {},
        headers: [Object],
        baseURL:
         'https://sheets.googleapis.com/v4/spreadsheets/1glk-vpeAsxeVn6wyhFcakXK-u1Ew03okfrey7bIlMsI',
        transformRequest: [Array],
        transformResponse: [Array],
        timeout: 0,
        adapter: [Function: httpAdapter],
        xsrfCookieName: 'XSRF-TOKEN',
        xsrfHeaderName: 'X-XSRF-TOKEN',
        maxContentLength: -1,
        validateStatus: [Function: validateStatus],
        data: undefined },
     request:
      ClientRequest {
        domain: null,
        _events: [Object],
        _eventsCount: 6,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: true,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: false,
        sendDate: false,
        _removedConnection: false,
        _removedContLen: false,
        _removedTE: false,
        _contentLength: 0,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket: [TLSSocket],
        connection: [TLSSocket],
        _header:
         'GET /v4/spreadsheets/1glk-vpeAsxeVn6wyhFcakXK-u1Ew03okfrey7bIlMsI/ HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nAuthorization: Bearer undefined\r\nUser-Agent: axios/0.19.2\r\nHost: sheets.googleapis.com\r\nConnection: close\r\n\r\n',
        _onPendingData: [Function: noopPendingOutput],
        agent: [Agent],
        socketPath: undefined,
        timeout: undefined,
        method: 'GET',
        path:
         '/v4/spreadsheets/1glk-vpeAsxeVn6wyhFcakXK-u1Ew03okfrey7bIlMsI/',
        _ended: true,
        res: [IncomingMessage],
        aborted: undefined,
        timeoutCb: null,
        upgradeOrConnect: false,
        parser: null,
        maxHeadersCount: null,
        _redirectable: [Writable],
        [Symbol(isCorked)]: false,
        [Symbol(outHeadersKey)]: [Object] },
     data: { error: [Object] } },
  isAxiosError: true,
  toJSON: [Function] }

该提问来源于开源项目:theoephraim/node-google-spreadsheet

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

7条回答

  • weixin_39531780 weixin_39531780 5月前

    closing this as I think it's an issue with your setup, not the module.

    点赞 评论 复制链接分享
  • weixin_39915171 weixin_39915171 5月前

    Iam using below code to update row values:

    
    var { GoogleSpreadsheet } = require('google-spreadsheet');
    var creds = require('./client_secret.json');
    var config = require('../../config');
    const _ = require('lodash');
    var prodReportSpreadsheet = new GoogleSpreadsheet(config.googleSheets.prodReport.spreadsheetId);
    exports.updateClientNameInReport = function (order, orgName) {
        return prodReportSpreadsheet.useServiceAccountAuth(creds)
            .then(function () {
                return prodReportSpreadsheet.loadInfo()
                    .then(function (info) {
                        const sheet = _.find(prodReportSpreadsheet.sheetsByIndex, { title: 'In Process' });
                        if (sheet) return sheet;
                        else throw { err: true, code: 'PTGS01' }  //sheet is not found
                    })
            })
            .then((sheetInfo) => {
                return recordToUpdate(order, sheetInfo)
                    .then((row) => {
                        if (row['Client Invoice #'] == order.Order_ID) {
                            row['Client'] = orgName;
                            return row.save();
                        } else return;
                    })
    
            })
    }
    
    点赞 评论 复制链接分享
  • weixin_39879674 weixin_39879674 5月前

    The bug is clear!. Your credentials are not valid!

    shell
     { Error: Google API error - [401] Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential
    
    点赞 评论 复制链接分享
  • weixin_39531780 weixin_39531780 5月前

    i think if you add a .catch you'll likely see an error when you try to initialize the service account auth.

    点赞 评论 复制链接分享
  • weixin_39915171 weixin_39915171 5月前

    The bug is clear!. Your credentials are not valid!

    shell
     { Error: Google API error - [401] Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential
    

    Hi, My credentials are valid only. My code is working fine for the this credentials. This error occurs only some times. If credentials are not valid then it should not update for some times right? This is the code Iam running https://github.com/theoephraim/node-google-spreadsheet/issues/307#issuecomment-590782021

    点赞 评论 复制链接分享
  • weixin_39915171 weixin_39915171 5月前

    i think if you add a .catch you'll likely see an error when you try to initialize the service account auth.

    Hi , It giving the same error in the .catch() block saying that Authentication error that I shared in the top of this thread. My code is working fine for the this credentials. This error occurs only some times. If credentials are not valid then it should not update for some times right? This is the code Iam running https://github.com/theoephraim/node-google-spreadsheet/issues/307#issuecomment-590782021

    点赞 评论 复制链接分享
  • weixin_39531780 weixin_39531780 5月前

    Are you calling useServiceAccountAuth multiple times? You should only call that once when the application starts up, rather than each time you are trying to update the sheet. It seems like that could be the issue if it is happening intermittently - one call is trying to reset the auth while another is in the middle of saving something.

    点赞 评论 复制链接分享

相关推荐