Unable to fetch data using axios

System Information
  • Strapi Version: v4.5.2
  • Operating System: macOS
  • Database: Localhost
  • Node Version: 16.13.0
  • NPM Version:
  • Yarn Version: 1.22.18

Thanks in advance for helping me figure this out. What I did:

  • Deployed Strapi Project
  • Deployed NextJs project
  • Installed and setup Axios to fetch data from strapi backend

but continue getting this error:

import axios from "axios";

export async function getServerSideProps(context) {
  const baseUrl = process.env.NEXT_PUBLIC_STRAPI_API_URL;

  try {
    const { data } = await axios.get(`${baseUrl}/users`, {
      headers: {
        Authorization: `bearer ${process.env.NEXT_PUBLIC_FORGEDMART_STRAPI_API_TOKEN}`,
      },
    });
    console.log(data);
  } catch (error) {
    console.log(error);
  }

  return {
    props: {
      session: await getSession(context),
    },
  };
}

//Error:

AxiosError: connect ECONNREFUSED ::1:1337
    at AxiosError.from (PATH-TO-FILE)
    at RedirectableRequest.handleRequestError (PATH-TO-FILE)
    at RedirectableRequest.emit (node:events:537:28)
    at eventHandlers.<computed> (/PATH-TO-FILE)
    at ClientRequest.emit (node:events:537:28)
    at Socket.socketErrorListener (node:_http_client:465:9)
    at Socket.emit (node:events:537:28)
    at emitErrorNT (node:internal/streams/destroy:151:8)
    at emitErrorCloseNT (node:internal/streams/destroy:116:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  port: 1337,
  address: '::1',
  syscall: 'connect',
  code: 'ECONNREFUSED',
  errno: -61,
  config: {
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    adapter: [Function: httpAdapter],
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    env: { FormData: [Function], Blob: [class Blob] },
    validateStatus: [Function: validateStatus],
    headers: AxiosHeaders {
      Authorization: 'bearer MY_BEARER_TOKEN',
      'User-Agent': 'axios/1.1.3',
      'Accept-Encoding': 'gzip, deflate, br',
      [Symbol(defaults)]: [Object]
    },
    method: 'get',
    url: 'http://localhost:1337/api/users',
    data: undefined
  },
  request: <ref *1> 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],
      socket: [Function: handleRequestSocket]
    },
    _eventsCount: 3,
    _maxListeners: undefined,
    _options: {
      maxRedirects: 21,
      maxBodyLength: Infinity,
      protocol: 'http:',
      path: '/api/users',
      method: 'GET',
      headers: [Object: null prototype],
      agents: [Object],
      auth: undefined,
      beforeRedirect: [Function: dispatchBeforeRedirect],
      beforeRedirects: [Object],
      hostname: 'localhost',
      port: '1337',
      agent: undefined,
      nativeProtocols: [Object],
      pathname: '/api/users'
    },
    _ended: true,
    _ending: true,
    _redirectCount: 0,
    _redirects: [],
    _requestBodyLength: 0,
    _requestBodyBuffers: [],
    _onNativeResponse: [Function (anonymous)],
    _currentRequest: ClientRequest {
      _events: [Object: null prototype],
      _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: [Socket],
      _header: 'GET /api/users HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'Authorization: bearer My_bearer_token \r\n' +
        'User-Agent: axios/1.1.3\r\n' +
        'Accept-Encoding: gzip, deflate, br\r\n' +
        'Host: localhost:1337\r\n' +
        'Connection: close\r\n' +
        '\r\n',
      _keepAliveTimeout: 0,
      _onPendingData: [Function: nop],
      agent: [Agent],
      socketPath: undefined,
      method: 'GET',
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      path: '/api/users',
      _ended: false,
      res: null,
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: 'localhost',
      protocol: 'http:',
      _redirectable: [Circular *1],
      [Symbol(kCapture)]: false,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype],
      [Symbol(kUniqueHeaders)]: null
    },
    _currentUrl: 'http://localhost:1337/api/users',
    [Symbol(kCapture)]: false
  },
  cause: Error: connect ECONNREFUSED ::1:1337
      at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1237:16) {
    errno: -61,
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '::1',
    port: 1337
  }
}
(node:8334) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)

did you enable access rights to this entity api in the ui?
Settings>Roles&Permissions>Roles>Authenticated

1 Like

Did anyone get the answer to this ?? I am getting the same error.

Change http://localhost:1337 to http://127.0.0.1:1337

2 Likes