• 28-Dec-2022
Lightrun Team
Author Lightrun Team
Share
Troubleshooting Common Issues in Axios - Axios

Troubleshooting Common Issues in Axios – Axios

Lightrun Team
Lightrun Team
28-Dec-2022

Project Description

 

Axios is a JavaScript library that provides a simple and powerful way to make HTTP requests from a web browser or Node.js. It is designed to be a lightweight and easy-to-use alternative to the built-in fetch function, with a similar API but with some additional features and capabilities.

Axios uses the modern Promise API, which allows you to use async/await syntax to make HTTP requests and handle responses in a more concise and readable way.

It also provides a number of other useful features, such as the ability to cancel requests, transform request and response data, and automatically retry failed requests.

 

Troubleshooting Axios – Axios with the Lightrun Developer Observability Platform

 

Getting a sense of what’s actually happening inside a live application is a frustrating experience, one that relies mostly on querying and observing whatever logs were written during development.
Lightrun is a Developer Observability Platform, allowing developers to add telemetry to live applications in real-time, on-demand, and right from the IDE.
  • Instantly add logs to, set metrics in, and take snapshots of live applications
  • Insights delivered straight to your IDE or CLI
  • Works where you do: dev, QA, staging, CI/CD, and production

The most common issues for Axios – Axios are:

 

Sending cookie with fetch is working but not with axios

 

Upon activating cross-site requests, axios appears to erase credentials and only maintain modified headers – despite utilizing ‘withCredentials’ option. Additionally, employing the transformRequest strategy for adding an extra header will additionally exclude previously included cookies from being passed along with the request.

const axiosInstance = axios.create({
    withCredentials: true,/
    headers: {
      'x-xsrf-token':  someCsrfToken,
    }
  });

without headers option:

with headers option:

 

Node.js axios upload large file using FormData, read all data to the memory, cause out of memory issue.

 

To reduce memory usage during large file uploads, try adding the maxRedirects: 0 option. This changes your transport from http/https to follow-redirects and can make a big difference while conserving resources. For those looking for an optimization solution, this is definitely worth exploring!

 

Passing array in query via axios

 

To pass an array in a query parameter using Axios, you can use the params property of the config object passed to the axios.get() method. The params property is an object that holds the key-value pairs of the query parameters.

For example, if you want to pass an array of numbers as a query parameter called numbers, you can do the following:

const numbers = [1, 2, 3];

axios.get('/api/endpoint', {
  params: {
    numbers
  }
});

This will send a request to the /api/endpoint with a query string that looks like this: ?numbers[]=1&numbers[]=2&numbers[]=3.

Note that the [] notation is used to denote an array of values for the same parameter. This is a common convention used in many languages and frameworks.

You can also pass an array of objects or strings in the same way:

const items = [
  { id: 1, name: 'Item 1' },
  { id: 2, name: 'Item 2' }
];

axios.get('/api/endpoint', {
  params: {
    items
  }
});

This will send a request to the /api/endpoint with a query string that looks like this: ?items[0][id]=1&items[0][name]=Item%201&items[1][id]=2&items[1][name]=Item%202.

 

Module not found: Error: Can’t resolve ‘url’ error with create-react-app/webpack 5

 

There are a few possible causes for this error:

  1. You might not have correctly installed the Axios library. Make sure you have installed Axios using the correct command: npm install axios or yarn add axios.
  2. You might have a typo in the import statement for Axios. Make sure you have correctly imported Axios in your code:
import axios from 'axios';
  1. You might be using an outdated version of create-react-app or webpack that has a bug related to the url module. Try upgrading to the latest version of create-react-app and webpack to see if that fixes the issue.
  2. You might have a conflicting dependency that is causing the url module to be missing. Try removing any unnecessary dependencies or trying the npm cache clean --force command to clear the cache and try reinstall the dependencies.

 

Restricted in strict mode, js engine: hermes (React Native + Axios 1.0.0)

 

An identical issue was encountered across three distinct RN projects, all running version 1.0.0 of the same package – resolving around axios interceptors usage in some form. The update to 0.27.2 has remedied this complication and operations are now functioning as expected once more!

 

POST FormData still creates Network Error on Android with 0.27.2

 

There are a few potential causes for this error:

  1. Make sure that the API endpoint you are trying to reach is correctly configured to accept FormData in the request body.
  2. Check the network connection on the Android device to ensure that it is stable and has a strong signal.
  3. Make sure that the FormData object is correctly constructed and that all required fields are included.
  4. If you are using a third-party library to handle the FormData, such as the form-data package, make sure that it is compatible with Axios and Android.
  5. Try using a different version of Axios to see if the issue persists. If you are using an older version of Axios (such as 0.27.2), try upgrading to the latest version to see if that resolves the issue.

 

[TypeError: Network request failed] either with fetch API or axios on android

 

There are a few potential causes for this error:

  1. Make sure that the API endpoint you are trying to reach is correctly configured and is accessible from the device.
  2. Check the network connection on the Android device to ensure that it is stable and has a strong signal.
  3. If you are using the fetch API, make sure that you have properly handled any errors that may occur. For example, you should add a .catch() block to your fetch request to handle any errors that may occur:
fetch(url)
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error(error));
  1. If you are using Axios, make sure that you have properly configured it to handle errors. You can use the .catch() method on the Axios promise to handle any errors that may occur:
axios.get(url)
  .then((response) => console.log(response.data))
  .catch((error) => console.error(error));
  1. If you are making a request to a third-party API, make sure that you have the correct API credentials and that you are using the correct API endpoint.

 

Uncaught Error: ES Modules may not assign module.exports or exports.*, Use ESM export syntax

 

This error usually occurs when you are trying to use the CommonJS module syntax (module.exports or exports.*) in a project that is using ECMAScript modules (ESM). In ESM, you should use the export keyword to export values from a module, rather than using module.exports or exports.*.

To fix this error, you should update your code to use the ESM export syntax. Here is an example of how you can export a value using ESM:

// In a module called "my-module.js"

export const foo = 'bar';

Then, in another module that wants to import the foo value, you can use the import keyword:

// In another module

import { foo } from './my-module';

console.log(foo); // Outputs "bar"

 

Is the breaking change in the type definition of AxiosError as intended?

 

With v0.27, it appears that the desired outcomes have been achieved!

if (e instanceof AxiosError) {
  console.log(e.response.data.message)
}

 

Change baseUrl after build via environment

 

It has been determined that the ENV variable API_URL is only consumed during application build time and not at runtime. This remains true even when launching an app with a docker-compose example.

frontend:
  image: test-frontend:latest
  ports:
    - "3000:3000"
  environment:
    - 'API_URL=http://pippo.test'

nuxt.config.js

  axios: {
    proxy: true,
    debug: true
  },
  proxy: {
    '/api': process.env.API_URL
  },

In order to ensure that all Axios requests are directed towards the same hostname + “/api”, it is necessary to set up a dynamic baseURL at run-time when deploying Nuxt in a Docker container. This allows for greater flexibility and ensures appropriate routing of calls regardless of address access.

 

Import axios from ‘axios’ results in undefined

 

Here are a few common causes:

  1. You may not have correctly installed the Axios library in your project. Make sure that you have run the correct installation command: npm install axios or yarn add axios.
  2. You may have a typo in your import statement. Make sure that you are using the correct import syntax: import axios from 'axios';.
  3. You may be trying to import Axios from the wrong location. Make sure that the Axios library is installed in the correct location and that you are using the correct path in your import statement.
  4. If you are using a bundler such as Webpack, there may be an issue with the way the Axios library is being bundled. Make sure that the Axios library is correctly included in your bundle.
  5. If you are using a transpiler such as Babel, there may be an issue with the way the Axios library is being transpiled. Make sure that the Axios library is correctly transpiled and that the correct file is being imported in your code.

 

Returning “Network Error” on unauthorized error (401)

 

There are a few potential causes for this error:

  1. Make sure that you are using the correct API endpoint and that you have the correct API credentials. If you are using an API that requires authentication, make sure that you have correctly configured Axios to include the necessary authentication headers in the request.
  2. Check the network connection to ensure that it is stable and has a strong signal.
  3. Make sure that the server is correctly configured to return a 401 error when the request is unauthorized.
  4. If you are using a third-party library to handle the authentication, make sure that it is compatible with Axios and that it is correctly configured.
  5. If you are using a version of Axios that is older than 0.19.0, you may be experiencing a bug that causes the “Network Error” to be returned instead of the actual error status code. Try upgrading to the latest version of Axios to see if that resolves the issue.

 

Why are null and undefined variables removed from params

 

All of these are possible: { key: undefined } to ? (not included) { key: null } to ?key { key: '' } to ?key= { key: 'null' } to ?key=null

 

Intercept not working with axios interceptors

 

Here are a few things you can try to troubleshoot this issue:

1. Make sure that you have correctly imported the Axios library into your project. You can import Axios using the following statement:

import axios from 'axios';

2. Make sure that you have correctly configured your interceptors. Here is an example of how you can set up an interceptor in Axios:

axios.interceptors.request.use(
  (config) => {
    // Modify the config object here
    return config;
  },
  (error) => {
    // Handle the error here
    return Promise.reject(error);
  }
);

3, Make sure that you are correctly handling any errors that may occur in your interceptors. If an error is thrown or returned from an interceptor, it will be passed down the chain of interceptors and eventually be rejected by the Axios promise.

4. If you are using a version of Axios that is older than 0.19.0, you may be experiencing a bug that prevents interceptors from working correctly. Try upgrading to the latest version of Axios to see if that resolves the issue.

 

Do not use localhost:3000 as default in production

 

It is generally not recommended to use localhost:3000 as the default API endpoint in a production environment.

localhost refers to the current device that the code is running on, so using localhost in a production environment will not work as expected. Instead, you should use the actual domain name or IP address of the server that is hosting the API.

For example, if your API is hosted at https://api.example.com, you should use that URL as the default endpoint in your production code.

If you need to use different API endpoints in different environments (e.g. development, staging, production), you can use environment variables or a configuration file to store the endpoint URLs and use the appropriate URL based on the current environment.

 

Axios module: axios.setToken where to run?

 

To refine the plugin, app.$axios can be directly accessed to call setToken – no need for imports and exports.

plugins/auth.js

export default ({store, app: { $axios }}) => {
  $axios.setToken(store.state.token)
}

 

networkError method should define a request attribute in mocked error response

 

Normalizing error objects ensures that a statusCode attribute is always included as the root property. The code attempts to retrieve this from an existing response before checking for one in the request and finally falling back on some default value if needed. Even when a status of “0” (zero) exists, it will be defined accordingly – such as with the current implementation done using Typescript.

interface RequestError extends AxiosError {
  status: number;
  data?: object;
}

function normalizeRequestError(error: AxiosError): RequestError {
  const {response, request} = error;
  if (response) {
    /*
     * The request was made and the server responded with a
     * status code that falls out of the range of 2xx
     */
    const {data, status: responseStatus} = response;
    return {
      ...error,
      status: responseStatus, // <- This would be zero in the mock returning [0, 'Network Error']
      data,
    };
  } else if (request) {
    /*
     * The request was made but no response was received, `error.request`
     * is an instance of XMLHttpRequest in the browser and an instance
     * of http.ClientRequest in Node.js
     */
    return {
      ...error,
      status: 0, //<- also set to zero in actual code
    };
  } else {
    //* Something happened in setting up the request and triggered an Error
    return {
      ...error,
      status: -1,
    };
  }
}

 

Enable axios to use the current domain as a host for client requests

 

For production, Apache is used to host the frontend static files, with no proxy in place; furthermore, development takes place utilizing single-page application mode. Incorporating axios into this setup allows it to utilize either the current browser domain axios: { browserBaseURL: "/" }

or a distinct port such as axios: { port: 8080, browserBaseURL: "/"} – though there appears to be an issue when employing that latter option.

To continue the work leverage a client-side plugin and configure it with axios as the base URL.

nuxt.config.js

  plugins: [
    "~/plugins/axios.client.js"
  ]

axios.client.js in /plugins

export default function({ $axios }) {
  if (process.client) {
    const host = window.location.hostname;
    $axios.setBaseURL("http://" + host + ":8080");
  }
}

All bases are covered – from the development of applications on local machines to running Docker in both a testing and production environment. With this setup, developers can ensure that their application runs seamlessly across multiple computing environments.

 

Is it possible to return the response data as a string?

 

Incorporating an array as opposed to an object into the second parameter of reply allows for flexibility in accepting any type.

 

Axios not receiving 204 response with Transfer-Encoding header in Node v14

 

There are a few potential causes for this issue:

  1. Make sure that the server is correctly configured to return a 204 response with a Transfer-Encoding: chunked header. If the server is not correctly configured, Axios will not be able to receive the response.
  2. Make sure that the Axios request is correctly configured to send and receive chunked responses. You can use the maxContentLength option to configure Axios to accept chunked responses:
axios.get('/api/endpoint', {
  maxContentLength: Infinity
});
  1. Make sure that you are using a version of Axios that is compatible with Node.js v14. If you are using an older version of Axios, there may be issues with compatibility that are causing the response to be lost.
  2. If you are using a third-party library to handle the HTTP requests, make sure that it is compatible with Axios and that it is correctly configured to send and receive chunked responses.

 

Cancellation may not work well with post

 

Axios uses the abort-controller package to implement cancellation, and this package works by canceling the underlying HTTP request. However, once the request has been sent to the server, it is up to the server to decide whether to honor the request to cancel the operation. Some servers may ignore the request to cancel and continue processing the request, while others may honor the request and stop processing it.

Therefore, it is generally recommended to use cancellation with caution, especially with POST requests that may have unintended consequences if they are canceled.

If you want to cancel a POST request in Axios, you can use the CancelToken feature to cancel the request before it is sent to the server. Here is an example of how you can use CancelToken to cancel a POST request in Axios:

import axios from 'axios';

const source = axios.CancelToken.source();

axios.post('/api/endpoint', {
  data: 'some data'
}, {
  cancelToken: source.token
}).catch((error) => {
  if (axios.isCancel(error)) {
    console.log('Request canceled');
  } else {
    console.error(error);
  }
});

// Later, to cancel the request:
source.cancel();

 

SSR: Axios request fails with 404 when using a proxy

 

Struggling with a .env variable named API_URL that was overriding ‘@nuxtjs/axios’ baseURL config? Fortunately, an illuminating solution by creating a demo project was prepared and shared. See the demonstration here.

Share

It’s Really not that Complicated.

You can actually understand what’s going on inside your live applications. It’s a registration form away.

Get Lightrun

Lets Talk!

Looking for more information about Lightrun and debugging?
We’d love to hear from you!
Drop us a line and we’ll get back to you shortly.

By submitting this form, I agree to Lightrun’s Privacy Policy and Terms of Use.