Error: Request failed with status code 501

I´m getting this error when I run this code in my job´s computer.

This is the code:

const { GoogleSpreadsheet } = require("google-spreadsheet");

const creds = require('./credentials.json');
const doc = new GoogleSpreadsheet('11NEx5WMijxjuAmT2cRuBDBzUMtS9d8hSirqi9YtAO-o'); // Please set your Spreadsheet ID.

const accessSheet = async () => {
  await doc.useServiceAccountAuth(creds);
  await doc.loadInfo();
  const worksheet = doc.sheetsByIndex[0];
  const rows = await worksheet.getRows();
  rows.forEach((row) => {
    console.log(row.Title);
  });
};
accessSheet();

This is the error message:

C:Usersrodrigo.pasiniDesktoprobo_grprnode_modulesaxioslibcorecreateError.js:16
var error = new Error(message);
^

Error: Request failed with status code 501
    at createError (C:Usersrodrigo.pasiniDesktoprobo_grprnode_modulesaxioslibcorecreateError.js:16:15)
    at settle (C:Usersrodrigo.pasiniDesktoprobo_grprnode_modulesaxioslibcoresettle.js:17:12)
    at IncomingMessage.handleStreamEnd (C:Usersrodrigo.pasiniDesktoprobo_grprnode_modulesaxioslibadaptershttp.js:269:11)
    at IncomingMessage.emit (node:events:402:35)
    at endReadableNT (node:internal/streams/readable:1343:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  config: {
    url: '/',
    method: 'get',
    headers: {
      Accept: 'application/json, text/plain, */*',
      Authorization: 'Bearer ya29.c.b0AXv0zTNo1VOXxOJkI-s603JwxUfimP6wwbgy21VJGc-a_pqL8g8x1ZBeKn6R8rQELVf7UJrhLxeSRaBDEIvl20IIrmdNzQ4rT-Ke9j2OVwGAeUgqJ3ju49RGU5gTYbX-ljGuWJ9bSjcR5yvUNTBZFRJRFgw939XhGPZnpioCFFDNHDR5I5k-xZGU6-EAPCT8mZufFMLHNFMLPMdx_zeAoj0YtqokAvM........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................',
      'User-Agent': 'axios/0.21.4',
      host: 'sheets.googleapis.com',
      'Proxy-Authorization': 'Basic cm9kcmlnby5wYXNpbmk6Um9kcmlnbzIyMTI='
    },
    params: {},
    baseURL: 'https://sheets.googleapis.com/v4/spreadsheets/11NEx5WMijxjuAmT2cRuBDBzUMtS9d8hSirqi9YtAO-o',
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    paramsSerializer: [Function: paramsSerializer],
    timeout: 0,
    adapter: [Function: httpAdapter],
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    validateStatus: [Function: validateStatus],
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    data: undefined
  },
  request: <ref *1> ClientRequest {
    _events: [Object: null prototype] {
      abort: [Function (anonymous)],
      aborted: [Function (anonymous)],
      connect: [Function (anonymous)],
      error: [Function (anonymous)],
      socket: [Function (anonymous)],
      timeout: [Function (anonymous)],
      prefinish: [Function: requestOnPrefinish]
    },
    _eventsCount: 7,
    _maxListeners: undefined,
    outputData: [],
    outputSize: 0,
    writable: true,
    destroyed: false,
    _last: true,
    chunkedEncoding: false,
    shouldKeepAlive: false,
    maxRequestsOnConnectionReached: false,
    _defaultKeepAlive: true,
    useChunkedEncodingByDefault: false,
    sendDate: false,
    _removedConnection: false,
    _removedContLen: false,
    _removedTE: false,
    _contentLength: 0,
    _hasBody: true,
    _trailer: '',
    finished: true,
    _headerSent: true,
    _closed: false,
    socket: <ref *2> Socket {
      connecting: false,
      _hadError: false,
      _parent: null,
      _host: 'proxypge01.pge.parana',
      _readableState: ReadableState {
        objectMode: false,
        highWaterMark: 16384,
        buffer: BufferList { head: null, tail: null, length: 0 },
        length: 0,
        pipes: [],
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: true,
        constructed: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        resumeScheduled: false,
        errorEmitted: false,
        emitClose: false,
        autoDestroy: true,
        destroyed: false,
        errored: null,
        closed: false,
        closeEmitted: false,
        defaultEncoding: 'utf8',
        awaitDrainWriters: null,
        multiAwaitDrain: false,
        readingMore: false,
        dataEmitted: true,
        decoder: null,
        encoding: null,
        [Symbol(kPaused)]: false
      },
      _events: [Object: null prototype] {
        end: [Function: onReadableStreamEnd],
        free: [Function: onFree],
        close: [ [Function: onClose], [Function: socketCloseListener] ],
        timeout: [Function: onTimeout],
        agentRemove: [Function: onRemove],
        error: [Function: socketErrorListener],
        finish: [Function: bound onceWrapper] { listener: [Function: destroy] }
      },
      _eventsCount: 7,
      _maxListeners: undefined,
      _writableState: WritableState {
        objectMode: false,
        highWaterMark: 16384,
        finalCalled: true,
        needDrain: false,
        ending: true,
        ended: true,
        finished: false,
        destroyed: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: false,
        bufferProcessing: false,
        onwrite: [Function: bound onwrite],
        writecb: null,
        writelen: 0,
        afterWriteTickInfo: null,
        buffered: [],
        bufferedIndex: 0,
        allBuffers: true,
        allNoop: true,
        pendingcb: 1,
        constructed: true,
        prefinished: false,
        errorEmitted: false,
        emitClose: false,
        autoDestroy: true,
        errored: null,
        closed: false,
        closeEmitted: false,
        [Symbol(kOnFinished)]: []
      },
      allowHalfOpen: false,
      _sockname: null,
      _pendingData: null,
      _pendingEncoding: '',
      server: null,
      _server: null,
      parser: null,
      _httpMessage: [Circular *1],
      [Symbol(async_id_symbol)]: 40,
      [Symbol(kHandle)]: TCP {
        reading: true,
        onconnection: null,
        [Symbol(owner_symbol)]: [Circular *2]
      },
      [Symbol(kSetNoDelay)]: false,
      [Symbol(lastWriteQueueSize)]: 0,
      [Symbol(timeout)]: null,
      [Symbol(kBuffer)]: null,
      [Symbol(kBufferCb)]: null,
      [Symbol(kBufferGen)]: null,
      [Symbol(kCapture)]: false,
      [Symbol(kBytesRead)]: 0,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(RequestTimeout)]: undefined
    },
    _header: 'GET https://sheets.googleapis.com/v4/spreadsheets/11NEx5WMijxjuAmT2cRuBDBzUMtS9d8hSirqi9YtAO-o/ HTTP/1.1rn' +
      'Accept: application/json, text/plain, */*rn' +
      'Authorization: Bearer ya29.c.b0AXv0zTNo1VOXxOJkI-s603JwxUfimP6wwbgy21VJGc-a_pqL8g8x1ZBeKn6R8rQELVf7UJrhLxeSRaBDEIvl20IIrmdNzQ4rT-Ke9j2OVwGAeUgqJ3ju49RGU5gTYbX-ljGuWJ9bSjcR5yvUNTBZFRJRFgw939XhGPZnpioCFFDNHDR5I5k-xZGU6-EAPCT8mZufFMLHNFMLPMdx_zeAoj0YtqokAvM........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................rn' +
      'User-Agent: axios/0.21.4rn' +
      'host: sheets.googleapis.comrn' +
      'Proxy-Authorization: Basic cm9kcmlnby5wYXNpbmk6Um9kcmlnbzIyMTI=rn' +
      'Connection: closern' +
      'rn',
    _keepAliveTimeout: 0,
    _onPendingData: [Function: nop],
    agent: Agent {
      _events: [Object: null prototype] {
        free: [Function (anonymous)],
        newListener: [Function: maybeEnableKeylog]
      },
      _eventsCount: 2,
      _maxListeners: undefined,
      defaultPort: 80,
      protocol: 'http:',
      options: [Object: null prototype] { path: null },
      requests: [Object: null prototype] {},
      sockets: [Object: null prototype] {
        'proxypge01.pge.parana:8080:': [
          <ref *2> Socket {
            connecting: false,
            _hadError: false,
            _parent: null,
            _host: 'proxypge01.pge.parana',
            _readableState: [ReadableState],
            _events: [Object: null prototype],
            _eventsCount: 7,
            _maxListeners: undefined,
            _writableState: [WritableState],
            allowHalfOpen: false,
            _sockname: null,
            _pendingData: null,
            _pendingEncoding: '',
            server: null,
            _server: null,
            parser: null,
            _httpMessage: [Circular *1],
            [Symbol(async_id_symbol)]: 40,
            [Symbol(kHandle)]: [TCP],
            [Symbol(kSetNoDelay)]: false,
            [Symbol(lastWriteQueueSize)]: 0,
            [Symbol(timeout)]: null,
            [Symbol(kBuffer)]: null,
            [Symbol(kBufferCb)]: null,
            [Symbol(kBufferGen)]: null,
            [Symbol(kCapture)]: false,
            [Symbol(kBytesRead)]: 0,
            [Symbol(kBytesWritten)]: 0,
            [Symbol(RequestTimeout)]: undefined
          }
        ]
      },
      freeSockets: [Object: null prototype] {},
      keepAliveMsecs: 1000,
      keepAlive: false,
      maxSockets: Infinity,
      maxFreeSockets: 256,
      scheduling: 'lifo',
      maxTotalSockets: Infinity,
      totalSocketCount: 1,
      [Symbol(kCapture)]: false
    },
    socketPath: undefined,
    method: 'GET',
    maxHeaderSize: undefined,
    insecureHTTPParser: undefined,
    path: 'https://sheets.googleapis.com/v4/spreadsheets/11NEx5WMijxjuAmT2cRuBDBzUMtS9d8hSirqi9YtAO-o/',
    _ended: true,
    res: IncomingMessage {
      _readableState: ReadableState {
        objectMode: false,
        highWaterMark: 16384,
        buffer: BufferList { head: null, tail: null, length: 0 },
        length: 0,
        pipes: [],
        flowing: true,
        ended: true,
        endEmitted: true,
        reading: false,
        constructed: true,
        sync: true,
        needReadable: false,
        emittedReadable: false,
        readableListening: false,
        resumeScheduled: false,
        errorEmitted: false,
        emitClose: true,
        autoDestroy: true,
        destroyed: true,
        errored: null,
        closed: true,
        closeEmitted: true,
        defaultEncoding: 'utf8',
        awaitDrainWriters: null,
        multiAwaitDrain: false,
        readingMore: true,
        dataEmitted: false,
        decoder: null,
        encoding: null,
        [Symbol(kPaused)]: false
      },
      _events: [Object: null prototype] {
        end: [ [Function: responseOnEnd], [Function: handleStreamEnd] ],
        data: [Function: handleStreamData],
        error: [Function: handleStreamError]
      },
      _eventsCount: 3,
      _maxListeners: undefined,
      socket: <ref *2> Socket {
        connecting: false,
        _hadError: false,
        _parent: null,
        _host: 'proxypge01.pge.parana',
        _readableState: ReadableState {
          objectMode: false,
          highWaterMark: 16384,
          buffer: BufferList { head: null, tail: null, length: 0 },
          length: 0,
          pipes: [],
          flowing: true,
          ended: false,
          endEmitted: false,
          reading: true,
          constructed: true,
          sync: false,
          needReadable: true,
          emittedReadable: false,
          readableListening: false,
          resumeScheduled: false,
          errorEmitted: false,
          emitClose: false,
          autoDestroy: true,
          destroyed: false,
          errored: null,
          closed: false,
          closeEmitted: false,
          defaultEncoding: 'utf8',
          awaitDrainWriters: null,
          multiAwaitDrain: false,
          readingMore: false,
          dataEmitted: true,
          decoder: null,
          encoding: null,
          [Symbol(kPaused)]: false
        },
        _events: [Object: null prototype] {
          end: [Function: onReadableStreamEnd],
          free: [Function: onFree],
          close: [ [Function: onClose], [Function: socketCloseListener] ],
          timeout: [Function: onTimeout],
          agentRemove: [Function: onRemove],
          error: [Function: socketErrorListener],
          finish: [Function: bound onceWrapper] {
            listener: [Function: destroy]
          }
        },
        _eventsCount: 7,
        _maxListeners: undefined,
        _writableState: WritableState {
          objectMode: false,
          highWaterMark: 16384,
          finalCalled: true,
          needDrain: false,
          ending: true,
          ended: true,
          finished: false,
          destroyed: false,
          decodeStrings: false,
          defaultEncoding: 'utf8',
          length: 0,
          writing: false,
          corked: 0,
          sync: false,
          bufferProcessing: false,
          onwrite: [Function: bound onwrite],
          writecb: null,
          writelen: 0,
          afterWriteTickInfo: null,
          buffered: [],
          bufferedIndex: 0,
          allBuffers: true,
          allNoop: true,
          pendingcb: 1,
          constructed: true,
          prefinished: false,
          errorEmitted: false,
          emitClose: false,
          autoDestroy: true,
          errored: null,
          closed: false,
          closeEmitted: false,
          [Symbol(kOnFinished)]: []
        },
        allowHalfOpen: false,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: null,
        _server: null,
        parser: null,
        _httpMessage: [Circular *1],
        [Symbol(async_id_symbol)]: 40,
        [Symbol(kHandle)]: TCP {
          reading: true,
          onconnection: null,
          [Symbol(owner_symbol)]: [Circular *2]
        },
        [Symbol(kSetNoDelay)]: false,
        [Symbol(lastWriteQueueSize)]: 0,
        [Symbol(timeout)]: null,
        [Symbol(kBuffer)]: null,
        [Symbol(kBufferCb)]: null,
        [Symbol(kBufferGen)]: null,
        [Symbol(kCapture)]: false,
        [Symbol(kBytesRead)]: 0,
        [Symbol(kBytesWritten)]: 0,
        [Symbol(RequestTimeout)]: undefined
      },
      httpVersionMajor: 1,
      httpVersionMinor: 1,
      httpVersion: '1.1',
      complete: true,
      rawHeaders: [
        'Server',
        'squid/3.4.8',
        'Mime-Version',
        '1.0',
        'Date',
        'Thu, 05 May 2022 17:03:37 GMT',
        'Content-Type',
        'text/html',
        'Content-Length',
        '0',
        'X-Squid-Error',
        'ERR_UNSUP_REQ 0',
        'X-Cache',
        'MISS from spge00007',
        'X-Cache-Lookup',
        'NONE from spge00007:8080',
        'Via',
        '1.1 spge00007 (squid/3.4.8)',
        'Connection',
        'close'
      ],
      rawTrailers: [],
      aborted: false,
      upgrade: false,
      url: '',
      method: null,
      statusCode: 501,
      statusMessage: 'Not Implemented',
      client: <ref *2> Socket {
        connecting: false,
        _hadError: false,
        _parent: null,
        _host: 'proxypge01.pge.parana',
        _readableState: ReadableState {
          objectMode: false,
          highWaterMark: 16384,
          buffer: BufferList { head: null, tail: null, length: 0 },
          length: 0,
          pipes: [],
          flowing: true,
          ended: false,
          endEmitted: false,
          reading: true,
          constructed: true,
          sync: false,
          needReadable: true,
          emittedReadable: false,
          readableListening: false,
          resumeScheduled: false,
          errorEmitted: false,
          emitClose: false,
          autoDestroy: true,
          destroyed: false,
          errored: null,
          closed: false,
          closeEmitted: false,
          defaultEncoding: 'utf8',
          awaitDrainWriters: null,
          multiAwaitDrain: false,
          readingMore: false,
          dataEmitted: true,
          decoder: null,
          encoding: null,
          [Symbol(kPaused)]: false
        },
        _events: [Object: null prototype] {
          end: [Function: onReadableStreamEnd],
          free: [Function: onFree],
          close: [ [Function: onClose], [Function: socketCloseListener] ],
          timeout: [Function: onTimeout],
          agentRemove: [Function: onRemove],
          error: [Function: socketErrorListener],
          finish: [Function: bound onceWrapper] {
            listener: [Function: destroy]
          }
        },
        _eventsCount: 7,
        _maxListeners: undefined,
        _writableState: WritableState {
          objectMode: false,
          highWaterMark: 16384,
          finalCalled: true,
          needDrain: false,
          ending: true,
          ended: true,
          finished: false,
          destroyed: false,
          decodeStrings: false,
          defaultEncoding: 'utf8',
          length: 0,
          writing: false,
          corked: 0,
          sync: false,
          bufferProcessing: false,
          onwrite: [Function: bound onwrite],
          writecb: null,
          writelen: 0,
          afterWriteTickInfo: null,
          buffered: [],
          bufferedIndex: 0,
          allBuffers: true,
          allNoop: true,
          pendingcb: 1,
          constructed: true,
          prefinished: false,
          errorEmitted: false,
          emitClose: false,
          autoDestroy: true,
          errored: null,
          closed: false,
          closeEmitted: false,
          [Symbol(kOnFinished)]: []
        },
        allowHalfOpen: false,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: null,
        _server: null,
        parser: null,
        _httpMessage: [Circular *1],
        [Symbol(async_id_symbol)]: 40,
        [Symbol(kHandle)]: TCP {
          reading: true,
          onconnection: null,
          [Symbol(owner_symbol)]: [Circular *2]
        },
        [Symbol(kSetNoDelay)]: false,
        [Symbol(lastWriteQueueSize)]: 0,
        [Symbol(timeout)]: null,
        [Symbol(kBuffer)]: null,
        [Symbol(kBufferCb)]: null,
        [Symbol(kBufferGen)]: null,
        [Symbol(kCapture)]: false,
        [Symbol(kBytesRead)]: 0,
        [Symbol(kBytesWritten)]: 0,
        [Symbol(RequestTimeout)]: undefined
      },
      _consuming: false,
      _dumped: false,
      req: [Circular *1],
      responseUrl: 'http://proxypge01.pge.parana:8080/https://sheets.googleapis.com/v4/spreadsheets/11NEx5WMijxjuAmT2cRuBDBzUMtS9d8hSirqi9YtAO-o/',
      redirects: [],
      [Symbol(kCapture)]: false,
      [Symbol(kHeaders)]: {
        server: 'squid/3.4.8',
        'mime-version': '1.0',
        date: 'Thu, 05 May 2022 17:03:37 GMT',
        'content-type': 'text/html',
        'content-length': '0',
        'x-squid-error': 'ERR_UNSUP_REQ 0',
        'x-cache': 'MISS from spge00007',
        'x-cache-lookup': 'NONE from spge00007:8080',
        via: '1.1 spge00007 (squid/3.4.8)',
        connection: 'close'
      },
      [Symbol(kHeadersCount)]: 20,
      [Symbol(kTrailers)]: null,
      [Symbol(kTrailersCount)]: 0,
      [Symbol(RequestTimeout)]: undefined
    },
    aborted: false,
    timeoutCb: null,
    upgradeOrConnect: false,
    parser: null,
    maxHeadersCount: null,
    reusedSocket: false,
    host: 'proxypge01.pge.parana',
    protocol: 'http:',
    _redirectable: Writable {
      _writableState: WritableState {
        objectMode: false,
        highWaterMark: 16384,
        finalCalled: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        destroyed: false,
        decodeStrings: true,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: true,
        bufferProcessing: false,
        onwrite: [Function: bound onwrite],
        writecb: null,
        writelen: 0,
        afterWriteTickInfo: null,
        buffered: [],
        bufferedIndex: 0,
        allBuffers: true,
        allNoop: true,
        pendingcb: 0,
        constructed: true,
        prefinished: false,
        errorEmitted: false,
        emitClose: true,
        autoDestroy: true,
        errored: null,
        closed: false,
        closeEmitted: false,
        [Symbol(kOnFinished)]: []
      },
      _events: [Object: null prototype] {
        response: [Function: handleResponse],
        error: [Function: handleRequestError]
      },
      _eventsCount: 2,
      _maxListeners: undefined,
      _options: {
        maxRedirects: 21,
        maxBodyLength: 10485760,
        protocol: 'http:',
        path: 'https://sheets.googleapis.com/v4/spreadsheets/11NEx5WMijxjuAmT2cRuBDBzUMtS9d8hSirqi9YtAO-o/',
        method: 'GET',
        headers: {
          Accept: 'application/json, text/plain, */*',
          Authorization: 'Bearer ya29.c.b0AXv0zTNo1VOXxOJkI-s603JwxUfimP6wwbgy21VJGc-a_pqL8g8x1ZBeKn6R8rQELVf7UJrhLxeSRaBDEIvl20IIrmdNzQ4rT-Ke9j2OVwGAeUgqJ3ju49RGU5gTYbX-ljGuWJ9bSjcR5yvUNTBZFRJRFgw939XhGPZnpioCFFDNHDR5I5k-xZGU6-EAPCT8mZufFMLHNFMLPMdx_zeAoj0YtqokAvM........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................',
          'User-Agent': 'axios/0.21.4',
          host: 'sheets.googleapis.com',
          'Proxy-Authorization': 'Basic cm9kcmlnby5wYXNpbmk6Um9kcmlnbzIyMTI='
        },
        agent: undefined,
        agents: { http: undefined, https: undefined },
        auth: undefined,
        hostname: 'proxypge01.pge.parana',
        port: '8080',
        beforeRedirect: [Function: beforeRedirect],
        nativeProtocols: {
          'http:': {
            _connectionListener: [Function: connectionListener],
            METHODS: [Array],
            STATUS_CODES: [Object],
            Agent: [Function],
            ClientRequest: [Function: ClientRequest],
            IncomingMessage: [Function: IncomingMessage],
            OutgoingMessage: [Function: OutgoingMessage],
            Server: [Function: Server],
            ServerResponse: [Function: ServerResponse],
            createServer: [Function: createServer],
            validateHeaderName: [Function: __node_internal_],
            validateHeaderValue: [Function: __node_internal_],
            get: [Function: get],
            request: [Function: request],
            maxHeaderSize: [Getter],
            globalAgent: [Getter/Setter]
          },
          'https:': {
            Agent: [Function: Agent],
            globalAgent: [Agent],
            Server: [Function: Server],
            createServer: [Function: createServer],
            get: [Function: get],
            request: [Function: request]
          }
        },
        pathname: 'https://sheets.googleapis.com/v4/spreadsheets/11NEx5WMijxjuAmT2cRuBDBzUMtS9d8hSirqi9YtAO-o/'
      },
      _ended: true,
      _ending: true,
      _redirectCount: 0,
      _redirects: [],
      _requestBodyLength: 0,
      _requestBodyBuffers: [],
      _onNativeResponse: [Function (anonymous)],
      _currentRequest: [Circular *1],
      _currentUrl: 'http://proxypge01.pge.parana:8080/https://sheets.googleapis.com/v4/spreadsheets/11NEx5WMijxjuAmT2cRuBDBzUMtS9d8hSirqi9YtAO-o/',
      [Symbol(kCapture)]: false
    },
    [Symbol(kCapture)]: false,
    [Symbol(kNeedDrain)]: false,
    [Symbol(corked)]: 0,
    [Symbol(kOutHeaders)]: [Object: null prototype] {
      accept: [ 'Accept', 'application/json, text/plain, */*' ],
      authorization: [
        'Authorization',
        'Bearer ya29.c.b0AXv0zTNo1VOXxOJkI-s603JwxUfimP6wwbgy21VJGc-a_pqL8g8x1ZBeKn6R8rQELVf7UJrhLxeSRaBDEIvl20IIrmdNzQ4rT-Ke9j2OVwGAeUgqJ3ju49RGU5gTYbX-ljGuWJ9bSjcR5yvUNTBZFRJRFgw939XhGPZnpioCFFDNHDR5I5k-xZGU6-EAPCT8mZufFMLHNFMLPMdx_zeAoj0YtqokAvM....................................................

When I run in my private computer, it´s run perfectly.

Why this happen? Someone know what’s happening?

How to fix React Hook “useAppContext” cannot be called in a class component Error?

I want to use useContext() inside componentDidMount() function because I need Id Partition inside it but it gave me error :
React Hook “useAppContext” cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function ?

 class Invhom extends Component {
   
            //...
    
     componentDidMount(){
                
             const {IdPartition,setIdPartition } = useAppContext();  // ... Error
            
                    let value = this.IdPartition;
                  //  console.log(value);
           axios.get('http://localhost:9091/inventaire/select_inventaire');
                  } }
            //...         
            }

//------------------------------context.js----------------------------------------


    export const AppContext = createContext(null);



    export function useAppContext() {
      return useContext(AppContext);
    }

How to return an async array from Express JS?

[I am trying to pass my getAll() method of the Container class, and show the objects that are in the products.txt file, however when I try to show it by the page path by express in res.send() it shows me only a empty object, but in the console it shows me the respective products that are in products.txt, it’s like I can’t find a way to show those objects in the browser, the method is asynchronous so it must be because of that, but no I find a way to fix it]

[app.js]

const fs = require("fs");

class Contenedor {
  constructor(txtNameFile) {
    this.txtNameFile = txtNameFile;
    this.products = [];
  }

  async fileInJSON() {
    let fileTxt = await fs.promises.readFile(this.txtNameFile, "utf-8");
    let type = JSON.parse(fileTxt);
    return type;
  }

  async fileSaving(item) {
    let type = JSON.stringify(item);
    await fs.promises.writeFile(this.txtNameFile, type);
  }

  async save(obj) {
    try {
      let fileTxt = await fs.promises.readFile(this.txtNameFile, "utf-8");
      if (fileTxt === "") {
        obj.id = 1;
        this.products.push(obj);
      } else {
        const type = JSON.parse(fileTxt);
        obj.id = type[type.length - 1].id + 1;
        type.push(obj);
        this.products = type;
        this.fileSaving(type);
      }
      console.log(
        "El producto se ha guardado en el archivo satisfactoriamente"
      );
      return obj.id;
    } catch (error) {
      console.error("No se ha podido guardar");
    }
  }

  async getById(id) {
    let type = await this.fileInJSON();
    let product = type.find((product) => product.id == id);
    return console.log(product);
  }

  async getAll() {
    let type = await this.fileInJSON();
    return console.log(type);
  }

  async deleteAll() {
    let item = [];
    this.products = item;
    this.fileSaving(item);
  }

  async deleteById(number) {
    let type = await this.fileInJSON();
    let item = type.find((item) => item.id === number);
    let index = type.indexOf(item);
    type.splice(index, 1);
    this.fileSaving(type);
  }
}

module.exports = Contenedor;

[appServer.js]

const express = require("express");
const app = express();
const PORT = 3000;
const Contenedor = require("./app.js");
const newShoeProduct = new Contenedor("./products.txt");

app.get("/", (req, res) => {
  res.send("Ingresa a la ruta /productos para ver los productos :D");
});

app.get("/productos", (req, res) => {
  res.send(JSON.stringify(newShoeProduct.getAll()));
});

console.log(newShoeProduct);
 

const servidor = app
  .listen(PORT, () => {
    console.log(`Servidor corriendo en el puerto ${PORT}`);
  })
  .on("error", (error) => console.error("FALLASTE" + error));

[products.txt]

[{"title":"Zapatillas Volcom urbanas","price":3000,"thumbnail":"https://http2.mlstatic.com/D_NQ_NP_938726-MLA31099290226_062019-O.webp","id":1},{"title":"Zapatillas DC dark","price":2100,"thumbnail":"https://http2.mlstatic.com/D_NQ_NP_737014-MLA41571053814_042020-O.webp","id":2},{"title":"Zapatillas Adidas deportivas","price":1500,"thumbnail":"https://http2.mlstatic.com/D_NQ_NP_771197-MLA49179920702_022022-O.webp","id":3} ]

How do I fix my discord bot being vulnerable to XSS

You could make a REST API that does JS code and it would run on the security risk line, how should I sanitize the input or validate it?

const { SlashCommandBuilder } = require('@discordjs/builders');
const { Client, Intents, DiscordAPIError } = require('discord.js');
const DiscordJS = require('discord.js')
const axios = require('axios').default;

module.exports = {
    data: new SlashCommandBuilder()
    .setName('httpget')
    .setDescription('HTTP get command!')
    .addStringOption(option =>
        option.setName('url')
        .setDescription('URL of the website')
        .setRequired(true)),
    async execute(interaction) {
        let text = interaction.options.getString('url') //option the user called the bot with
        axios.get(text).then(resp => {  //requet using said URL
            const contenttotext = `${JSON.stringify(console.log("PWN"))}` //SECURITY RISK
            
            interaction.reply({
            content: contenttotext    //sends it back
             })
    }) .catch(function (error) {
        // handle error
      });
    }
};

JavaScript confirm() with php script get, cancel script? [duplicate]

How could I cancel my function on the else? I tried to use alert, text, but even if that show me the text, the member is still delete after that.

<div class="show_n_react_div_deux">
  <a onclick="deleteUser()" id="ban" href="ban.php?id=<?php echo $user['id']; ?>"><img src="../images/delete.png" width="50"></a>
  <script>
    function deleteUser() {
      let text = "are you sure you want to delete this member?";

      if (confirm(text) == true) {
        text = "You pressed OK!";
      } else {
        cancel(deleteUser());
      }
    }
  </script>
</div>
                   

view :

enter image description here

How to remove repeated code for ternary operator?

I’m receiving the data where a lot of fields are null, and I have to populate something if the field is null.

like in the below data

{   //...
    IGM_ETD: '2021-11-27T23:59:00+05:00',
    milestatus: null,
    transit_depart: null,
    etd_atd: null,
    // around 200+ fields
 }

As here, the transit_depart is null, I’m using the ternary operator to put something in return if the data is null like this ;

// this is a reproducible example, there are some other styles and comp to display if/else part
{transit_depart ? <>{transit_depart}</> : <>Not Available<>}

This is working as expected but the problem is I have around 200+ fields like this and if I follow this then in the future if we have to make any UI change then we will be changing all the relevant code here. So how to avoid it or how can we can manage this.

put i18next value inside variable JS

i have a JS code that changes the text after some time and i want to use i18next translations in that to make the words “performance, flexibility” etc.. be in more than 1 language. the idea i had to solve this was putting the i18next value inside a variable and substitue the words in the JS code with the variables. but i don’t know how to use i18next to put his translated words inside a variable, if someone could help me i would be very grateful!

Json files

en-US

"index" : {
"performance" : " performance",
"flexibility" : "flexibility"
}

pt-PT

"index" : {
"performance" : " Desempenho",
"flexibility" : "Flexibilidade"
}

JS code

var typed1 = new Typed('#typed1', {
strings: ["performance", "flexibility", "scalability."],
typeSpeed: 50,
backSpeed: 20,
smartBackspace: true,
loop: true
});
var typed1 = new Typed('#typed2', {
strings: ["Protection", "Sophisticated", "Flexibility"],
typeSpeed: 100,
backSpeed: 50,
smartBackspace: true,
loop: true
});

pass data to child component when clicked on card in parent component ( card has image name id and more info ) angular

I want to pass data when clicked on the card(card has images, id, name, and more) from the parent(nfts) to the child(main) component and render the information in the child component.

I tried to use @Input() but I don’t get the value on the child component, and also tried using the EventEmitter but I could not pass the value via the variable.emit(value)
or is there a better way achieve this

stackbliz link –
https://github.com/HemanthGirimath/nft-cryptoPunk-clone

‘Row’ cannot be used as a JSX component

I am using react-bootstrap components (Row, Col) in a tsx component it some how returned me an error of :
” (alias) class Col<As extends React.ElementType = “div”>
import Col
‘Col’ cannot be used as a JSX component.
Its instance type ‘Col<“div”>’ is not a valid JSX element.”
it was working fine before today.
any suggestions on how to fix that ?!?

Parsing a user-input value

I would like to allow a user to enter some input, and the program to parse that as a js type, if it can. For example, in what the user types into the text input is:

  • Hello -> “Hello” (string)
  • 2.13 -> 2.13 (number)
  • true -> true (bool)

Would the following accomplish this in a very basic fashion, ignoring nested objects and such?

function parseValueFromText(text) {
    try {
        return JSON.parse(text);
    } catch(e) {
        if (e instanceof SyntaxError) {
            return text;
        } else {
            throw e;
        }
    }
}
let a=parseValueFromText('hello'),
    b=parseValueFromText(123);
console.log(a, typeof a);
console.log(b, typeof b);

NODEJS, how do I correctly export this method of my Container class to another JS file where I manage express?

[I’m trying to pass my getAll() method of my Container class found in app.js to my appServer.js file to pass it to the res.send() of my app = express() variable
and pass that res.send() to the route “/products”

when I try to run the server it throws me an error telling me that Container.getAll() is not a function

I have tried to export using exports.getAll()
but it still throws me an error]

[App.js]

const fs = require("fs");

class Contenedor {
  constructor(txtNameFile) {
    this.txtNameFile = txtNameFile;
    this.products = [];
  }

  async fileInJSON() {
    let fileTxt = await fs.promises.readFile(this.txtNameFile, "utf-8");
    let type = JSON.parse(fileTxt);
    return type;
  }

  async fileSaving(item) {
    let type = JSON.stringify(item);
    await fs.promises.writeFile(this.txtNameFile, type);
  }

  async save(obj) {
    try {
      let fileTxt = await fs.promises.readFile(this.txtNameFile, "utf-8");
      if (fileTxt === "") {
        obj.id = 1;
        this.products.push(obj);
      } else {
        const type = JSON.parse(fileTxt);
        obj.id = type[type.length - 1].id + 1;
        type.push(obj);
        this.products = type;
        this.fileSaving(type);
      }
      console.log(
        "El producto se ha guardado en el archivo satisfactoriamente"
      );
      return obj.id;
    } catch (error) {
      console.error("No se ha podido guardar");
    }
  }

  async getById(id) {
    let type = await this.fileInJSON();
    let product = type.find((product) => product.id == id);
    return console.log(product);
  }

  async getAll() {
    let type = await this.fileInJSON();
    return console.log(type);
  }

  async deleteAll() {
    let item = [];
    this.products = item;
    this.fileSaving(item);
  }

  async deleteById(number) {
    let type = await this.fileInJSON();
    let item = type.find((item) => item.id === number);
    let index = type.indexOf(item);
    type.splice(index, 1);
    this.fileSaving(type);
  }
}

module.exports = Contenedor;

[appServer.js]

const express = require("express");
const app = express();
const PORT = 3000;
const Contenedor = require("./app.js");
 

app.get("/", (req, res) => {
  res.send("Ingresa a la ruta /productos para ver los productos :D");
});

app.get("/productos", (req, res) => {
  res.send(Contenedor.getAll());
});

const servidor = app
  .listen(PORT, () => {
    console.log(`Servidor corriendo en el puerto ${PORT}`);
  })
  .on("error", (error) => console.error("FALLASTE" + error));

Froala, create a boostrap table after pasting data from an excel file

This is what I have so far:
https://jsfiddle.net/kenpy/241L8ubo/66/

Im working with froala Editor, I need to paste the content of an excel into my froala then with that data I have to build a boostrap table that adds columns(n times) dynamically depending on how many my excel has.

I already achieved that with the code on my sample and always using a standard format for the excel.

The sample looks like this after I paste the excel content:
enter image description here

The problem I have is when trying to fill the rest of the data into the right columns

First I declared my variable

let rows = [];

Then I push data inside the rows array

//INSERTAMOS EL RESTO DE LOS DATOS
if (fila > 4) {
  if(columna==1){
    agrupacion = colVal.trim();
  }
  if (columna >= 2) {
    year = f + columna - 2;
    var valor = colVal.trim();
    rows.push({"agrupacion": agrupacion, "valor": valor, "year": year});
    year++;
  }
}

I get something that looks like this:

 rows = [{
      agrupacion: "Total país",
      valor: "81.8",
      year: 2015
    }, {
      agrupacion: "Total país",
      valor: "86.4",
      year: 2016
    }, {
      agrupacion: "Total país",
      valor: "67.3",
      year: 2017
    }, {
      agrupacion: "Total país",
      valor: "70.8",
      year: 2018
    }, {
      agrupacion: "Total país",
      valor: "67.6",
      year: 2019
    },...

This is the part where I use that array of objects to feed data into my table but is not working

$('#tabla_grafico').bootstrapTable('load', rows);

So I replaced that with this:

$('#tabla_grafico').bootstrapTable('refresh', { url: 'inc/datos-graficos-data.php?q=test&datos='+rows });

The problem is that the var row it sends like this [object object],[object object],… rather than the actual values.

How to handle promises when using (call, bind, apply) with JavaScript functions?

I have a function like so:

let maybeRun = function (cb: Function, allow: boolean, ctx: object = window) {
    return function () {
        if (!allow) return;

        cb.call(ctx, ...arguments);
        // cb.apply(ctx, arguments);
    };
};

In case cb is synchronous there is no problem, but how should I handle the case of cb returns a promise (asynchronous)?

let cb = async ()=> {...};

let foo = maybeRun(cb, true);

await foo()

I want the returned function foo to have same behaviour of cb (sync or async).