GET Request Query Params with Axios

The easiest way to make a GET request with Axios is the axios.get() function . The 2nd parameter to axios.get() is the Axios options : Axios will serialize options.params and add it to the query string for you as shown below.

You can set options.params to a POJO as shown above, or to an instance of the JavaScript's built-in URLSearchParams class .

Customizing Serialization

Axios's built-in query string serializer respects the toJSON() function , so it automatically serializes built-in custom JSON serialization, like Moment objects or Mongoose documents .

However, if you need more flexibility in how Axios serializes query strings, Axios supports a paramsSerializer option that lets you overwrite the function Axios to serialize.

More Axios Tutorials

  • Configuring maxBodyLength in Axios
  • How to Send Headers With an Axios POST Request
  • HTTP DELETE Requests with Body in Axios
  • How to Use JSON with Axios
  • How to Use the User-Agent Header in Axios
  • Axios Multipart Form Data
  • How to use Axios' create() Method with POST Requests

Mastering Axios

  • GET Requests
  • Get the HTTP Response Body
  • POST Requests
  • PUT Requests
  • DELETE Requests
  • The then() Function
  • Error Handling using catch()
  • Calling Axios as a Function

Framework Features

  • The create() Function
  • Axios Interceptors

Integrations

DEV Community

DEV Community

Mastering JS

Posted on Jun 23, 2021

Setting the Request Method with Axios

Axios is our recommended JavaScript HTTP client. While we are opposed to unnecessary outside dependencies, Axios has several advantages over fetch() :

  • Axios is isomorphic, fetch is not
  • Axios throws an error when a request fails
  • Automatic JSON and Form-Encoded Serialization and Parsing
  • Interceptors and instances

Another reason is that Axios has neat helper methods that allow you to set the request method, like GET or POST . For example, below is how you can send an HTTP GET request with Axios .

Want to send a POST request ? That's easy, just change get() for post() and pass the request body as the 2nd parameter.

Calling Axios as a Function

If you prefer the named parameters approach that fetch() uses, you can also set the request method by setting the method option as shown below.

Top comments (0)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

devmirx profile image

Learn React Hydration in 5 minutes

LordCodex - Apr 22

jkettmann profile image

Path To A Clean(er) React Architecture - API Layer & Fetch Functions

Johannes Kettmann - Apr 26

ellis22 profile image

ES6 Spread Operator: Unleashing the Power of Modern JavaScript

Ellis - Apr 22

nirazanbasnet profile image

Building a simple language switcher in a vue.js: Step-by-step tutorial 🌐

⚡ Nirazan Basnet ⚡ - Apr 26

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

  • Books Get Your Hands Dirty on Clean Architecture Stratospheric
  • Contribute Become an Author Writing Guide Author Workflow Author Payment
  • Services Book me Advertise
  • Categories Spring Boot Java Node Kotlin AWS Software Craft Simplify! Meta Book Reviews

Complete Guide to Axios HTTP Client

  • May 20, 2022

Making API calls is integral to most applications and while doing this we use an HTTP client usually available as an external library. Axios is a popular HTTP client available as a JavaScript library with more than 22 million weekly downloads as of May 2022.

We can make API calls with Axios from JavaScript applications irrespective of whether the JavaScript is running on the front-end like a browser or the server-side.

In this article, we will understand Axios and use its capabilities to make different types of REST API calls from JavaScript applications.

Example Code

Why do we need axios.

Let us first understand why do we need to use a library like Axios. JavaScript already provides built-in objects: XMLHttpRequest and the Fetch API for interacting with APIs.

Axios in contrast to these built-in objects is an open-source library that we need to include in our application for making API calls over HTTP. It is similar to the Fetch API and returns a JavaScript Promise object but also includes many powerful features.

One of the important capabilities of Axios is its isomorphic nature which means it can run in the browser as well as in server-side Node.js applications with the same codebase.

Axios is also a promise-based HTTP client that can be used in plain JavaScript as well as in advanced JavaScript frameworks like React, Vue.js, and Angular.

It supports all modern browsers, including support for IE 8 and higher.

In the following sections, we will look at examples of using these features of Axios in our applications.

Installing Axios and Other Prerequisites For the Examples

We have created the following applications to simulate APIs on the server consumed by other applications on the server and the browser with REST APIs :

Applications

  • apiserver : This is a Node.js application written using the Express Framework that will contain the REST APIs.
  • serversideapps : This is also a Node.js written in Express that will call the REST APIs exposed by the apiserver application using the Axios HTTP client.
  • reactapp : This is a front-end application written in React which will also call the REST APIs exposed by the apiserver application.

Instead of Express, we could have used any other JavaScript framework or even raw JavaScript applications. To understand Express, please refer to our Express series of articles starting with Getting started on Express .

We will need to install the Axios library in two of these applications: serversideapps and reactapp which will be making API calls. Let us change to these directories one by one and install Axios using npm :

The package.json in our Node.js express application after installing the axios module looks like this:

We can see the axios module added as a dependency in the dependencies element.

If we want to call APIs with Axios from a vanilla JavaScript application, then we need to include it from a Content delivery network (CDN) as shown here:

After setting up our applications, let us now get down to invoking the APIs exposed by the apiserver from the serversideapp and the reactapp using the Axios HTTP client in the following sections.

Sending Requests with the Axios Instance

Let us start by invoking a GET method with the Axios HTTP client from our server-side application: serversideapp .

For doing this, we will add an Express route handler function with a URL: /products to the application. In the route handler function, we will fetch the list of products by calling an API from our apiserver with the URL: http://localhost:3002/products .

We will use the signature: axios(config) on the default instance provided by the Axios HTTP client for doing this:

In this example, we are first calling require('axios') for getting an instance: axios set up with a default configuration.

Then we are passing a configuration argument to the axios instance containing the method parameter set to the HTTP method: get and the url parameter set to the URL of the REST endpoint: http://localhost:3002/products . The url parameter is mandatory while we can omit the method parameter that will then default to get .

This method returns a JavaScript Promise object which means the program does not wait for the method to complete before trying to execute the subsequent statement. The Promise is either fulfilled or rejected, depending on the response from the API.

We use the then() method as in this example for processing the result. The then() method gets executed when the Promise is fulfilled . In our example, in the then method, we are extracting the list of products by calling apiResponse.data .

Similarly, a POST request for adding a new product made with the axios default instance will look like this:

In this example, in addition to what we did for calling the GET method, we have set the data element containing the JSON representation of the new Product along with an Authorization header. We are processing the response in the then function on the Promise response where we are extracting the API response data by calling apiResponse.data .

For more involved processing of the API response, it will be worthwhile to understand all the elements of the response returned by the API call made with axios :

  • data : Response payload sent by the server
  • status : HTTP status code from the server response
  • statusText : HTTP status message from the server response
  • headers : HTTP headers received in the API response
  • config : config sent to the axios instance for sending the request
  • request : Request that generated this response. It is the last ClientRequest instance in node.js (in redirects) and an XMLHttpRequest instance in the browser.

Sending Requests with the Convenience Instance Methods of Axios

Axios also provides an alternate signature for making the API calls by providing convenience methods for all the HTTP methods like: axios.get() , axios.post() , axios.put() , axios.delete() , etc.

We can write the previous example for calling the GET method of the REST API using the convenience method: axios.get() as shown below:

In this example, in the Express route handler function, we are calling the get() method on the default instance of axios and passing the URL of the REST API endpoint as the sole argument. This code looks much more concise than the signature: axios(config) used in the example in the previous section.

The signature: axios.get() is always preferable for calling the REST APIs due to its cleaner syntax. However, the signature: axios(config) of passing a config object containing the HTTP method, and URL parameters to the axios instance can be used in situations where we want to construct the API calls dynamically.

The get() method returns a JavaScript Promise object similar to our earlier examples, where we extract the list of products inside the then function.

Instead of appending the request query parameter in the URL in the previous example, we could have passed the request parameter in a separate method argument: params as shown below:

We could have also used the async/await syntax to call the get() method:

async/await is part of ECMAScript 2017 and is not supported in older browsers like IE.

Let us next make a POST request to an API with the convenience method axios.post() :

Here we are using the async/await syntax to make a POST request with the axios.post() method. We are passing the new product to be created as a JSON as the second parameter of the post() method.

Using Axios in Front-End Applications

Let us look at an example of using Axios in a front-end application built with the React library. The below snippet is from a React component that calls the API for fetching products:

As we can see, the code for making the API call with Axios is the same as what we used in the Node.js application in the earlier sections.

Sending Multiple Concurrent Requests with Axios

In many situations, we need to combine the results from multiple APIs to get a consolidated result. With the Axios HTTP client, we can make concurrent requests to multiple APIs as shown in this example:

In this example, we are making requests to two APIs using the Promise.all() method. We pass an iterable of the two Promise objects returned by the two APIs as input to the method.

In response, we get a single Promise object that resolves to an array of the results of the input Promise objects.

This Promise object returned as the response will resolve only when all of the input promises are resolved, or if the input iterable contains no promises .

Overriding the default Instance of Axios

In all the examples we have seen so far, we used the require('axios') to get an instance of axios which is configured with default parameters. If we want to add a custom configuration like a timeout of 2 seconds, we need to use Axios.create() where we can pass the custom configuration as an argument.

An Axios instance created with Axios.create() with a custom config helps us to reuse the provided configuration for all the API invocations made by that particular instance.

Here is an example of an axios instance created with Axios.create() and used to make a GET request:

In this example, we are using axios.create() to create a new instance of Axios with a custom configuration that has a base URL of http://localhost:3002/products and a timeout of 1000 milliseconds. The configuration also has an Accept and Authorization headers set depending on the API being invoked.

The timeout configuration specifies the number of milliseconds before the request times out. If the request takes longer than the timeout interval, the request will be aborted.

Intercepting Requests and Responses

We can intercept requests or responses of API calls made with Axios by setting up interceptor functions. Interceptor functions are of two types:

  • Request interceptor for intercepting requests before the request is sent to the server.
  • Response interceptor for intercepting responses received from the server.

Here is an example of an axios instance configured with a request interceptor for capturing the start time and a response interceptor for computing the time taken to process the request:

In this example, we are setting the request.time to the current time in the request interceptor. In the response interceptor, we are capturing the current time in response.config.time.endTime and computing the duration by deducting from the current time, the start time captured in the request interceptor.

Interceptors are a powerful feature that can be put to use in many use cases where we need to perform actions common to all API calls. In the absence of interceptors, we will need to repeat these actions in every API call. Some of these examples are:

  • Verify whether the access token for making the API call has expired in the request interceptor. If the token has expired, fetch a new token with the refresh token.
  • Attach specific headers required by the API to the request in the request interceptor. For example, add the Authorization header to every API call.
  • Check for HTTP status, headers, and specific fields in the response to detect error conditions and trigger error handling logic.

Handling Errors in Axios

The response received from Axios is a JavaScript promise which has a then() function for promise chaining, and a catch() function for handling errors. So for handling errors, we should add a catch() function at the end of one or more then() functions as shown in this example:

In this example, we have put the error handling logic in the catch() function. The callback function in the catch() takes the error object as input. We come to know about the source of the error by checking for the presence of the response property and request property in the error object with error.response and error.request .

An error object with a response property indicates that our server returned a 4xx/5xx error and accordingly return a helpful error message in the response.

In contrast, An error object with a request property indicates network errors, a non-responsive backend, or errors caused by unauthorized or cross-domain requests.

The error object may not have either a response or request object attached to it. This indicates errors related to setting up the request, which eventually triggered the error. An example of this condition is an URL parameter getting omitted while sending the request.

Cancelling Initiated Requests

We can also cancel or abort a request when we no longer require the requested data for example, when the user navigates from the current page to another page. To cancel a request, we use the AbortController class as shown in this code snippet from our React application:

As we can see in this example, we are first creating a controller object using the AbortController() constructor, then storing a reference to its associated AbortSignal object using the signal property of the AbortController .

When the axios request is initiated, we pass in the AbortSignal as an option inside the request’s options object: {signal: abortSignal} . This associates the signal and controller with the axios request and allows us to abort the request by calling the abort() method on the controller .

Using Axios in TypeScript

Let us now see an example of using Axios in applications authored in TypeScript.

We will first create a separate folder: serversideapp_ts and create a project in Node.js by running the below command by changing into this directory:

Let us next add support for TypeScript to our Node.js project by performing the following steps:

  • Installing Typescript and ts-node with npm :
  • Creating a JSON file named tsconfig.json with the below contents in our project’s root folder to specify different options for compiling the TypeScript code:
  • Installing the axios module with npm :

Axios includes TypeScript definitions, so we do not have to install them separately.

After enabling the project for TypeScript, let us add a file index.ts which will contain our code for making API calls with Axios in TypeScript.

Next, we will make an HTTP GET request to our API for fetching products as shown in this code snippet:

In this example, we are getting the axios instance by importing it from the module in the first line. We have next defined two type definitions: Product and GetProductsResponse .

After that we have defined a method getProducts() where we are invoking the API with the axios.get() method using the async/await syntax. We are passing the URL of the API endpoint and an Accept header to the axios.get() method.

Let us now run this program with the below command:

We are calling the method: getProducts() in the last line in the program, which prints the response from the API in the terminal/console.

In this article, we looked at the different capabilities of Axios. Here is a summary of the important points from the article:

  • Axios is an HTTP client for calling REST APIs from JavaScript programs running in the server as well as in web browsers.
  • We create default instance of axios by calling require('axios')
  • We can override the default instance of axios with the create() method of axios to create a new instance, where we can override the default configuration properties like ‘timeout’.
  • Axios allows us to attach request and response interceptors to the axios instance where we can perform actions common to multiple APIs.
  • Error conditions are handled in the catch() function of the Promise response.
  • We can cancel requests by calling the abort() method of the AbortController class.
  • The Axios library includes TypeScript definitions, so we do not have to install them separately when using Axios in TypeScript applications.

You can refer to all the source code used in the article on Github .

axios assignment to property of function parameter 'config'

Software Engineer, Consultant and Architect with current expertise in Enterprise and Cloud Architecture, serverless technologies, Microservices, and Devops.

Recent Posts

Optimizing Node.js Application Performance with Caching

Optimizing Node.js Application Performance with Caching

Olaoluwa Ajibade

  • April 20, 2024

Endpoints or APIs that perform complex computations and handle large amounts of data face several performance and responsiveness challenges. This occurs because each request initiates a computation or data retrieval process from scratch, which can take time.

Bubble Sort in Kotlin

Bubble Sort in Kotlin

  • Ezra Kanake
  • April 14, 2024

Bubble Sort, a basic yet instructive sorting algorithm, takes us back to the fundamentals of sorting. In this tutorial, we’ll look at the Kotlin implementation of Bubble Sort, understanding its simplicity and exploring its limitations.

Quick Sort in Kotlin

Quick Sort in Kotlin

Sorting is a fundamental operation in computer science and Quick Sort stands out as one of the most efficient sorting algorithms.

Advisory boards aren’t only for executives. Join the LogRocket Content Advisory Board today →

LogRocket blog logo

  • Product Management
  • Solve User-Reported Issues
  • Find Issues Faster
  • Optimize Conversion and Adoption
  • Start Monitoring for Free

How to make HTTP requests with Axios

axios assignment to property of function parameter 'config'

Editor’s note : Updated on 29 November 2023, this tutorial covers Axios usage with async/await for better code maintenance and Axios error handling.

How to Make HTTP Requests with Axios

Axios is a client HTTP API based on the XMLHttpRequest interface provided by browsers. In this tutorial, we’ll demonstrate how to make HTTP requests using Axios with clear examples, including how to make an Axios POST request with axios.post() , how to send multiple requests simultaneously with Promise.all , and much more.

If you’re more of a visual learner, check out the video tutorial below:

Why use Axios?

The most common way for frontend programs to communicate with servers is through the HTTP protocol. You are probably familiar with the Fetch API and the XMLHttpRequest interface, which allows you to fetch resources and make HTTP requests.

If you’re using a JavaScript library, chances are it comes with a client HTTP API. jQuery’s $.ajax() function, for example, has been particularly popular with frontend developers. But as developers move away from such libraries in favor of native APIs, dedicated HTTP clients have emerged to fill the gap.

As with Fetch, Axios is promise-based. However, it provides a more powerful and flexible feature set. Advantages of using Axios over the native Fetch API include:

  • Request and response interception
  • Streamlined error handling
  • Protection against XSRF
  • Support for upload progress
  • Support for older browsers
  • Automatic JSON data transformation

Installing Axios

You can install Axios using:

The Bower package manager:

Or a content delivery network:

How to make an Axios POST request

Making an HTTP request is as easy as passing a config object to the axios function. You can make a POST request using Axios to “post” data to a given endpoint and trigger events. To perform an HTTP POST request in Axios, call axios.post() .

Making a POST request in Axios requires two parameters: the URI of the service endpoint and an object that contains the properties you wish to send to the server.

For a simple Axios POST request, the config object must have a url property. If no method is provided, GET will be used as the default value.

Let’s look at a simple Axios POST example:

This should look familiar to those who have worked with jQuery’s $.ajax function. This code is instructing Axios to send a POST request to /login with an object of key/value pairs as its data. Axios will automatically convert the data to JSON and send it as the request body.

Shorthand methods for Axios HTTP requests

Axios also provides a set of shorthand methods for performing different types of requests. The methods are as follows:

  • axios.request(config)
  • axios.get(url[, config])
  • axios.delete(url[, config])
  • axios.head(url[, config])
  • axios.options(url[, config])
  • axios.post(url[, data[, config]])
  • axios.put(url[, data[, config]])
  • axios.patch(url[, data[, config]])

For instance, the following code shows how the previous example could be written using the axios.post() method:

What does axios.post return?

Once an HTTP POST request is made, Axios returns a promise that is either fulfilled or rejected, depending on the response from the backend service.

To handle the result, you can use the then() method, like this:

If the promise is fulfilled, the first argument of then() will be called; if the promise is rejected, the second argument will be called. According to the Axios documentation , the fulfillment value is an object containing the following properties:

As an example, here’s how the response looks when requesting data from the GitHub API:

Using Axios with async and await

The async and await syntax is syntactic sugar around the Promises API. It helps you write cleaner, more readable, and maintainable code. With async and await , your codebase feels synchronous and easier to think about.

When using async and await , you invoke axios or one of its request methods inside an asynchronous function, like in the example below:

When using the async and await syntax, it is standard practice to wrap your code in a try-catch block. Doing so will ensure you appropriately handle errors and provide feedback for a better user experience.

Using Promise.all to send multiple requests

You can use Axios with Promise.all to make multiple requests in parallel by passing an iterable of promises to it. The Promise.all static method returns a single promise object that fulfills only when all input promises have fulfilled.

Here’s a simple example of how to use Promise.all to make simultaneous HTTP requests:

This code makes two requests to the GitHub API and then logs the value of the created_at property of each response to the console. Keep in mind that if any of the input promises reject, then the promise will immediately reject with the reason of the first promise that rejects.

Be aware that Axios also has two built-in functions, axios.all and axios.spread , that are deprecated. You may encounter them frequently in legacy code, but do not use them in new projects.

axios assignment to property of function parameter 'config'

Over 200k developers use LogRocket to create better digital experiences

axios assignment to property of function parameter 'config'

The axios.all function is similar to the Promise.all static method described above. On the other hand, axios.spread is a convenient method to assign the properties of the response array to separate variables. You can use array destructuring instead of axios.spread .

Here’s how you could use axios.all and axios.spread :

The output of this code is the same as the previous example. The only difference is that we used axios.all and axios.spread instead.

Sending custom headers with Axios

Sending custom headers with Axios is straightforward. Simply pass an object containing the headers as the last argument. For example:

Axios timeout settings

When making a network request to a server, it is not uncommon to experience delays when the server takes too long to respond. It is standard practice to timeout an operation and provide an appropriate error message if a response takes too long. This ensures a better user experience when the server is experiencing downtime or a higher load than usual.

With Axios, you can use the timeout property of your config object to set the waiting time before timing out a network request. Its value is the waiting duration in milliseconds. The request is aborted if Axios doesn’t receive a response within the timeout duration. The default value of the timeout property is 0 milliseconds (no timeout).

You can check for the ECONNABORTED error code and take appropriate action when the request times out:

You can also timeout a network request using the AbortSignal.timeout static method. It takes the timeout as an argument in milliseconds and returns an AbortSignal instance. You need to set it as the value of the signal property.

The network request aborts when the timeout expires. Axios sets the value of error.code to ERR_CANCELED and error.message to canceled :

POST JSON with Axios

Axios automatically serializes JavaScript objects to JSON when passed to the axios.post function as the second parameter. This eliminates the need to serialize POST bodies to JSON.

Axios also sets the Content-Type header to application/json . This enables web frameworks to automatically parse the data.

More great articles from LogRocket:

  • Don't miss a moment with The Replay , a curated newsletter from LogRocket
  • Learn how LogRocket's Galileo cuts through the noise to proactively resolve issues in your app
  • Use React's useEffect to optimize your application's performance
  • Switch between multiple versions of Node
  • Discover how to use the React children prop with TypeScript
  • Explore creating a custom mouse cursor with CSS
  • Advisory boards aren’t just for executives. Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.

If you want to send a preserialized JSON string to axios.post() JSON, you’ll need to make sure the Content-Type header is set.

Transforming requests and responses

Although Axios automatically converts requests and responses to JSON by default, it also allows you to override the default behavior and define a different transformation mechanism. This is particularly useful when working with an API that accepts only a specific data format, such as XML or CSV.

To change request data before sending it to the server, set the transformRequest property in the config object. Note that this method only works for PUT , POST , DELETE , and PATCH request methods.

Here’s an example of how to use transformRequest in Axios:

To modify the data before passing it to then() or catch() , you can set the transformResponse property:

Intercepting requests and responses

HTTP interception is a popular feature of Axios. With this feature, you can examine and change HTTP requests from your program to the server and vice versa, which is very useful for a variety of implicit tasks, such as logging and authentication.

At first glance, interceptors look very much like transforms, but they differ in one key way: unlike transforms, which only receive the data and headers as arguments, interceptors receive the entire response object or request config.

You can declare a request interceptor in Axios like this:

This code logs a message to the console whenever a request is sent and then waits until it gets a response from the server, at which point it prints the time the account was created at GitHub to the console. One advantage of using interceptors is that you no longer have to implement tasks for each HTTP request separately.

Axios also provides a response interceptor, which allows you to transform the responses from a server on their way back to the application:

Client-side support for protection against XSRF

Cross-site request forgery (or XSRF for short) is a method of attacking a web-hosted app in which the attacker disguises themself as a legal and trusted user to influence the interaction between the app and the user’s browser. There are many ways to execute such an attack, including XMLHttpRequest .

Fortunately, Axios is designed to protect against XSRF by allowing you to embed additional authentication data when making requests. This enables the server to discover requests from unauthorized locations.

Here’s how this can be done with Axios:

Monitoring POST request progress

Another interesting feature of Axios is the ability to monitor request progress. This is especially useful when downloading or uploading large files. The example provided in the Axios documentation gives you a good idea of how that can be done. But for the sake of simplicity and style, we are going to use the Axios Progress Bar module in this tutorial.

The first thing we need to do to use this module is to include the related style and script:

Then we can implement the progress bar like this:

To change the default styling of the progress bar, we can override the following style rules:

Canceling requests

In some situations, you may no longer care about the result and want to cancel a request that’s already been sent. This can be done by using AbortController . You can create an AbortController instance and set its corresponding AbortSignal instance as the value of the signal property of the config object.

Here’s a simple example:

Axios also has a built-in function for canceling requests. However, the built-in CancelToken functionality is deprecated. You may still encounter it in legacy codebase, but it is not advisable to use it in new projects.

Below is a basic example:

You can also create a cancel token by passing an executor function to the CancelToken constructor, as shown below:

Axios error handling

An HTTP request may succeed or fail. Therefore, it is important to handle errors on the client side and provide appropriate feedback for a better user experience.

Possible causes of error in a network request may include server errors, authentication errors, missing parameters, and requesting non-existent resources.

Axios, by default, rejects any response with a status code that falls outside the successful 2xx range. However, you can modify this feature to specify what range of HTTP codes should throw an error using the validateStatus config option, like in the example below:

The error object that Axios passes to the .catch block has several properties, including the following:

In addition to the properties highlighted above, if the request was made and the server responded with a status code that falls outside the 2xx range, the error object will also have the error.response object.

On the other hand, if the request was made but no response was received, the error object will have an error.request object. Depending on the environment, the error.request object is an instance of XMLHttpRequest in the browser environment and an instance of http.ClientRequest in Node.

You need to check for error.response and error.request objects in your .catch callback to determine the error you are dealing with so that you can take an appropriate action:

However, sometimes duplicating the code above in the .catch callback for each request can become tedious and time-consuming. You can instead intercept the error and handle it globally like so:

Popular Axios libraries

Axios’ rise in popularity among developers has resulted in a rich selection of third-party libraries that extend its functionality. From testers to loggers, there’s a library for almost any additional feature you may need when using Axios. Here are some libraries that are currently available:

  • axios-vcr : Records and replays requests in JavaScript
  • axios-response-logger : Axios interceptor that logs responses
  • axios-method-override : Axios request method override plugin
  • axios-extensions : Axios extensions lib, including throttle and cache GET request features
  • axios-api-versioning : Add easy-to-manage API versioning to Axios
  • axios-cache-plugin : Helps you cache GET requests when using Axios
  • axios-cookiejar-support : Adds tough-cookie support to Axios
  • react-hooks-axios : Custom React Hooks for Axios
  • moxios : Mock Axios requests for testing
  • redux-saga-requests : Redux-Saga add-on to simplify handling AJAX requests
  • axios-fetch : Web API Fetch implementation backed by an Axios client
  • axios-curlirize : Logs any Axios request as a curl command in the console
  • axios-actions : Bundles endpoints as callable, reusable services
  • mocha-axios : HTTP assertions for Mocha using Axios
  • axios-mock-adapter : Axios adapter that allows you to easily mock requests
  • axios-debug-log : Axios interceptor of logging request and response with debug library
  • redux-axios-middleware : Redux middleware for fetching data with Axios HTTP client
  • axiosist : Axios-based supertest that converts the Node.js request handler to an Axios adapter; used for Node.js server unit test

Browser support

When it comes to browser support, Axios is very reliable. Even older browsers such as IE 11 work well with Axios:

Wrapping up

There’s a good reason Axios is so popular among developers: it’s packed with useful features. In this post, we’ve taken a look at several key features of Axios and learned how to use them in practice. But there are still many aspects of Axios that we haven’t discussed. Be sure to check out the Axios GitHub page to learn more.

Do you have some tips on using Axios? Let us know in the comments!

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Facebook (Opens in new window)

axios assignment to property of function parameter 'config'

Stop guessing about your digital experience with LogRocket

Recent posts:.

Comparing Mutative Vs Immer Vs Reducers For Data Handling In React

Comparing React state tools: Mutative vs. Immer vs. reducers

Mutative processes data with better performance than both Immer and native reducers. Let’s compare these data handling options in React.

axios assignment to property of function parameter 'config'

Radix UI adoption guide: Overview, examples, and alternatives

Radix UI is quickly rising in popularity and has become an excellent go-to solution for building modern design systems and websites.

axios assignment to property of function parameter 'config'

Understanding the CSS revert-layer keyword

In this article, we’ll explore CSS cascade layers — and, specifically, the revert-layer keyword — to help you refine your styling strategy.

axios assignment to property of function parameter 'config'

Exploring Nushell, a Rust-powered, cross-platform shell

Nushell is a modern, performant, extensible shell built with Rust. Explore its pros, cons, and how to install and get started with it.

axios assignment to property of function parameter 'config'

5 Replies to "How to make HTTP requests with Axios"

You should also note that axios can also be used on the server with node.js – probably one of my favorite higher level HTTP libraries.

One of the better qualities when using it on the server is the ability to create an instance with defaults – for example sometimes I’ll need to access another REST API to integrate another service with one of our products, if there is no existing package or the existing package doesn’t support the end points I need to access I’ll just create an abstraction which internally uses a http client created by axios.create():

const instance = axios.create({ baseURL: ‘https://api.example.org/’, headers: {‘Some-Auth-Header’: ‘token’} });

Cheers, Chris

Can you please answer this?

https://stackoverflow.com/questions/58996278/how-to-send-binary-stream-from-string-content-to-third-party-api-using-axios-nod

This post says nothing about the responseType parameter, which can stream a large binary file.

Got a question about accessing the data outside of the axios.spread. What I am doing is using node to collate some data from disparate API calls and return one dataset. I do the two calls, create a new object and return it. The new object exists within the AXIS code block but when I try and view outside it is blank.

I also tried to do this in a function with a return but it also returns a blank.

let retData = {}; axios .all([reqDevInfo, reqConInfo]) .then( axios.spread((resDevInfo,resConInfo ) => { retData.status = 200; retData.deviceName = deviceName retData.tenant = resDevInfo.data.results[0].tenant.name; retData.ru = resDevInfo.data.results[0].position; retData.TServerName = resConInfo.data.results[0].connected_endpoint.device.name; retData.TServerPort = resConInfo.data.results[0].cable.label; console.log(retData); // this print the expected data

}) ) .catch(errors => { // react on errors. console.error(errors);

console.log(retData) // this is blank

How can I build or append data elements to a post request before I send the request? I have optional 4 optional parameters and there are too many combinations to code for all the variations.

Leave a Reply Cancel reply

Peter Mekhaeil

Add custom config to axios requests.

Axios supports adding custom config to requests that can be used later throughout the request.

Here is an example adding a custom config called endpointName :

It can be used in interceptors :

It is also included in Axios errors:

TypeScript support

Create an axios.d.ts and add the custom config under AxiosRequestConfig :

Getting Started

Promise based HTTP client for the browser and node.js

What is Axios?

Axios is a promise-based HTTP Client for node.js and the browser. It is isomorphic (= it can run in the browser and nodejs with the same codebase). On the server-side it uses the native node.js http module, while on the client (browser) it uses XMLHttpRequests.

  • Make XMLHttpRequests from the browser
  • Make http requests from node.js
  • Supports the Promise API
  • Intercept request and response
  • Transform request and response data
  • Cancel requests
  • Query parameters serialization with support for nested entries
  • JSON ( application/json )
  • Multipart / FormData ( multipart/form-data )
  • URL encoded form ( application/x-www-form-urlencoded )
  • Posting HTML forms as JSON
  • Automatic JSON data handling in response
  • Progress capturing for browsers and node.js with extra info (speed rate, remaining time)
  • Setting bandwidth limits for node.js
  • Compatible with spec-compliant FormData and Blob (including node.js )
  • Client side support for protecting against XSRF

Using bower:

Using yarn:

Using jsDelivr CDN:

Using unpkg CDN:

Prebuilt CommonJS modules for direct importing with require (if your module bundler failed to resolve them automatically)

How to include query parameters in GET request with Axios

Axios is a promise-based HTTP client that allows you to make HTTP requests in both the browser and Node.js with the same codebase. On the server-side, it uses the native Node.js http module, while on the client (browser), it relies on XMLHttpRequests .

There is a difference between query parameters and path parameters in the context of RESTful APIs:

  • Path parameters are part of the URL path itself, commonly used for unique identifiers, appear as segments within the URL, separated by slashes.
  • Query parameters are appended after the URL path, starting with a ? . They are used to filter, sort, or modify the resources.

This tutorial will focus on how to include query parameters in GET requests made with Axios.

Using plain object for params option

This is the recommended and most common approach. You define your query parameters as an object and pass it to the params property of the configuration object in the axios.get() method.

Axios automatically serializes the object into a query string and appends it to the URL. The serialization process involves converting the key-value pairs of the object into a URL-encoded format.

Using a plain object directly translates your data structure into query parameters, making the code intuitive and easier to understand. Adding or removing parameters simply involves modifying the object, keeping the code organized and adaptable.

You have less control over the exact formatting of the query string, such as array handling or custom separators. Special characters in parameter values might require manual encoding if not handled automatically by Axios.

Using a plain object as params in GET requests with Axios is a good choice for simplicity, readability, and flexibility, especially for basic use cases. However, if you need fine-grained control over query string formatting or work with complex data structures, URLSearchParams might be a better fit.

Using URLSearchParams for params option

When you need more control over query string formatting (array handling, separators, encoding), you can also create an instance of URLSearchParams class and pass it as the params option.

URLSearchParams is a built-in JavaScript object specifically designed to create and manage query parameters for URLs. It offers several advantages over using plain objects as params in GET requests:

  • It automatically serializes arrays using the specified array bracket notation (e.g., key[]=value1&key[]=value2 ), ensuring correct interpretation by servers.
  • It handles URL encoding automatically, preventing issues with special characters (spaces, periods, hyphens, underscores, tildes, exclamation marks, asterisk, parentheses, apostrophes, plus signs, commas, forward slashes, backslashes, percent signs, number signs, at signs, equal signs, question marks, ampersands).
  • No reliance on implicit object property names, preventing naming conflicts that can occur with plain objects.

Customizing Serialization

Axios automatically serializes query parameters, but you can customize it further using the paramsSerializer option:

While paramsSerializer in Axios offers customization for serialization, you generally don’t need to use it for most GET requests as Axios handles basic cases well.

If you need to format your data in a way that doesn’t match the default Axios handling, paramsSerializer provides control. For example:

  • Formatting dates in a specific format
  • Serializing nested objects in a custom way
  • Handling arrays with non-standard separators

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Passing custom props via axios config #2295

@Alex-Sokolov

Alex-Sokolov commented Jul 18, 2019

  • 👍 20 reactions

@Alex-Sokolov

idseventeen commented Jul 23, 2019

Sorry, something went wrong.

@Christilut

Christilut commented Jul 25, 2019 • edited

  • 👍 10 reactions

@ggedde

ggedde commented Jul 25, 2019

@eric7578

eric7578 commented Jul 26, 2019

@SevenGuns

SevenGuns commented Jul 26, 2019

@TvojTatk0

TvojTatk0 commented Jul 29, 2019

  • 👍 1 reaction

@yosimasu

yosimasu commented Aug 6, 2019

@webliving

webliving commented Aug 12, 2019

@jmike

jmike commented Aug 12, 2019

Alex-sokolov commented aug 12, 2019.

@justLuiz

webliving commented Oct 10, 2019

@lynnic26

lynnic26 commented Oct 11, 2019 • edited

  • 👍 9 reactions
  • 😄 1 reaction

@Ragash

Ragash commented Oct 12, 2019

@Ragash

Flyrell commented Oct 12, 2019

  • 🎉 1 reaction

@imshenshen

imshenshen commented Oct 14, 2019

@Askadias

Askadias commented Oct 20, 2019

@liamwang

liamwang commented Oct 29, 2019

@viulu5824

viulu5824 commented Nov 4, 2019

@yasuf

yasuf commented Nov 4, 2019

  • 👍 2 reactions
  • 👍 6 reactions

@johnculviner

johnculviner commented Nov 8, 2019

@artursudnik

artursudnik commented Nov 12, 2019

@isimonov

isimonov commented Nov 13, 2019

Flyrell commented nov 13, 2019.

@Flyrell

cristianocca commented Nov 18, 2019

@elonmir

elonmir commented Nov 19, 2019

@AndyOGo

AndyOGo commented Dec 5, 2019

@neizmirasego

neizmirasego commented Dec 5, 2019

@Garwin4j

Garwin4j commented Dec 5, 2019

@mbaev

mbaev commented Dec 8, 2019

@astronati

astronati commented Dec 9, 2019

@ricardoboss

ricardoboss commented Dec 17, 2019

@chinesedfan

chinesedfan commented Dec 28, 2019

@chinesedfan

Levayv commented Jan 16, 2020

@rwam

rwam commented Jan 17, 2020

  • 🎉 7 reactions

@axios

No branches or pull requests

@Garwin4j

no-param-reassign

Disallow reassigning function parameters

Assignment to variables declared as function parameters can be misleading and lead to confusing behavior, as modifying function parameters will also mutate the arguments object when not in strict mode (see When Not To Use It below). Often, assignment to function parameters is unintended and indicative of a mistake or programmer error.

This rule can be also configured to fail when function parameters are modified. Side effects on parameters can cause counter-intuitive execution flow and make errors difficult to track down.

Rule Details

This rule aims to prevent unintended behavior caused by modification or reassignment of function parameters.

Examples of incorrect code for this rule:

Examples of correct code for this rule:

This rule takes one option, an object, with a boolean property "props" , and arrays "ignorePropertyModificationsFor" and "ignorePropertyModificationsForRegex" . "props" is false by default. If "props" is set to true , this rule warns against the modification of parameter properties unless they’re included in "ignorePropertyModificationsFor" or "ignorePropertyModificationsForRegex" , which is an empty array by default.

Examples of correct code for the default { "props": false } option:

Examples of incorrect code for the { "props": true } option:

Examples of correct code for the { "props": true } option with "ignorePropertyModificationsFor" set:

Examples of correct code for the { "props": true } option with "ignorePropertyModificationsForRegex" set:

When Not To Use It

If you want to allow assignment to function parameters, then you can safely disable this rule.

Strict mode code doesn’t sync indices of the arguments object with each parameter binding. Therefore, this rule is not necessary to protect against arguments object mutation in ESM modules or other strict mode functions.

This rule was introduced in ESLint v0.18.0.

Further Reading

Avatar image for spin.atomicobject.com

  • Rule source
  • Tests source

How to change the Base URL in Axios [4 ways]

avatar

Last updated: Mar 7, 2024 Reading time · 4 min

banner

# Table of Contents

  • Setting the axios Base URL globally
  • Overwriting the current base URL for a specific axios request
  • Setting the axios Base URL by creating an instance
  • Setting the axios Base URL dynamically

# Setting the axios Base URL globally

One way to change the axios base URL is to set the defaults.baseURL property on the imported axios object.

Properties set on the defaults object are applied to every request.

setting axios base url globally

You can import the axios module and set the defaults.baseURL property in your main .js file (e.g. index.js ).

You might also be making requests to the same origin and just want to set a path that you don't want to repeat every time.

The example sets the base URL to /api/ , so it would make an HTTP request to /api/posts on the same origin.

When you set properties on the defaults object, they are applied to every request as shown in this section of the axios docs.

# Overwriting the current base URL for a specific axios request

You can also overwrite the current base URL for a specific axios request.

Here is an example.

overwriting current base url for specific axios request

We initially set the baseUrl property to google.com .

Instead, we called the axios() method and passed it an object containing 3 properties:

  • method - the request method that is used when making the HTTP request.
  • url - the server URL to which the request is made
  • baseURL - baseURL will be prepended to url , unless url is absolute.

The example makes an HTTP GET request to the following URL:

You can view all the available properties you can set in the request configuration object in this section of the axios docs.

If you need to make a request to the current origin when overwriting the baseURL property, set baseURL to / .

The example makes an HTTP GET request to the current origin at /posts .

# Setting the axios Base URL by creating an instance

You can also set the base URL by creating an axios instance .

setting axios base url by creating an instance

We created an axios instance and set the baseURL property.

Now every time you make an HTTP request to the given URL, you have to import and use the instance instead of importing axios directly.

You can create a utility file called axios-instances.js that stores your axios instances.

You can now import the placeholderApi instance from the axios-instances module.

You can repeat the process and create multiple axios instances if you need to make HTTP requests to multiple different domains in the same application.

I've written a detailed guide on how to import and export classes and functions in JavaScript .

# Setting the axios Base URL dynamically

In some cases, you might also have to set the axios Base URL dynamically.

We created an axios instance and used the interceptors property to intercept the HTTP request before it is handled.

The request interceptor awaits an async function to determine the base URL.

After the base URL is retrieved, we issue the HTTP GET request.

The example makes an HTTP GET request to the following URL.

I've also written articles on:

  • Making HTTP requests with Axios in TypeScript
  • How to fetch Data on Button click in React
  • How to handle Timeouts when using Axios [3 easy Ways]
  • How to use Basic Auth with Axios in JavaScript

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

COMMENTS

  1. Assignment to property of function parameter no-param-reassign

    function createEmployee(emp) { // ⛔️ Assignment to property of function parameter 'emp'. eslint no-param-reassign. emp.name = 'bobby hadz'; emp.salary = 500; return emp; } The ESLint rule forbids assignment to function parameters because modifying a function's parameters also mutates the arguments object and can lead to confusing behavior.

  2. javascript

    Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question.Provide details and share your research! But avoid …. Asking for help, clarification, or responding to other answers.

  3. Request Config

    Request Config. These are the available config options for making requests. Only the url is required. Requests will default to GET if method is not specified. {// `url` is the server URL that will be used for the request url: '/user', // `method` is the request method to be used when making the request method: 'get', // default // `baseURL` will be prepended to `url` unless `url` is absolute.

  4. Config Defaults

    Config will be merged with an order of precedence. The order is library defaults found in lib/defaults/index.js, then defaults property of the instance, and finally config argument for the request. The latter will take precedence over the former. Here's an example. // Create an instance using the config defaults provided by the library// At ...

  5. Axios Options

    Axios' `options` parameter contains numerous options for configuring HTTP requests. Here's what you need to know.

  6. Custom properties for config · Issue #2203 · axios/axios · GitHub

    The request can safely be retried after it failed with the provided config. resolves axios#1628 * Fix a typo in README * Fix grammar in README.md * Axios create url bug * Fix axios#2234 * added spacing --eslint * added test cases * removed unexpected cases after updating the code * Fixing set `config.method` after mergeConfig for Axios ...

  7. GET Request Query Params with Axios

    Axios's built-in query string serializer respects the toJSON() function, so it automatically serializes built-in custom JSON serialization, like Moment objects or Mongoose documents.

  8. Setting the Request Method with Axios

    Calling Axios as a Function. If you prefer the named parameters approach that fetch() uses, you can also set the request method by setting the method option as shown below.

  9. Complete Guide to Axios HTTP Client

    Here we are using the async/await syntax to make a POST request with the axios.post() method. We are passing the new product to be created as a JSON as the second parameter of the post() method.. Using Axios in Front-End Applications. Let us look at an example of using Axios in a front-end application built with the React library. The below snippet is from a React component that calls the API ...

  10. How to make HTTP requests with Axios

    To perform an HTTP POST request in Axios, call axios.post(). Making a POST request in Axios requires two parameters: the URI of the service endpoint and an object that contains the properties you wish to send to the server. For a simple Axios POST request, the config object must have a url property.

  11. Add custom config to Axios requests

    Add custom config to Axios requests. Axios supports adding custom config to requests that can be used later throughout the request. Here is an example adding a custom config called endpointName: const instance = axios. create (); const { data} = await instance. get ("/api", { endpointName: "myApi"}); It can be used in interceptors:

  12. Getting Started

    Getting Started. Promise based HTTP client for the browser and node.js. What is Axios? Axios is a promise-based HTTP Client for node.js and the browser. It is isomorphic (= it can run in the browser and nodejs with the same codebase). On the server-side it uses the native node.js http module, while on the client (browser) it uses XMLHttpRequests.. Features

  13. How to include query parameters in GET request with Axios

    Axios is a promise-based HTTP client that allows you to make HTTP requests in both the browser and Node.js with the same codebase. On the server-side, it uses the native Node.js http module, while on the client (browser), it relies on XMLHttpRequests. There is a difference between query parameters and path parameters in the context of RESTful APIs:

  14. Making HTTP requests with Axios in TypeScript

    The signature of the axios.patch() method is the same as axios.post().. The method takes the data as the second argument and automatically converts it to JSON, so we don't have to use the JSON.stringify() method manually.. We only destructured the data property from the response in the examples, but you might have to use other properties from the response.

  15. Passing custom props via axios config · Issue #2295

    Attach axios 0.19 (uncomment line with [email protected]) Run fiddle (console show undefined) Expected behavior Custom config parameter passed. Or the ability to use another config option to pass custom data. Environment: Axios Version 0.18/0.19; Additional context/Screenshots First messages with axios 0.18, second with 0.19

  16. no-param-reassign

    If you want to allow assignment to function parameters, then you can safely disable this rule. Strict mode code doesn't sync indices of the arguments object with each parameter binding. Therefore, this rule is not necessary to protect against arguments object mutation in ESM modules or other strict mode functions. Version

  17. React Axios how to correctly pass in config as parameter?

    axios(url, { headers, method: 'POST', data: jsondata }),I tried this it works , but not when I call this function fetchWithToken(url,{method:'POST',data:jsondata}). My point is to call this function when calling API with different methods -

  18. How to change the Base URL in Axios [4 ways]

    #Table of Contents. Setting the axios Base URL globally; Overwriting the current base URL for a specific axios request; Setting the axios Base URL by creating an instance; Setting the axios Base URL dynamically # Setting the axios Base URL globally One way to change the axios base URL is to set the defaults.baseURL property on the imported axios object.. Properties set on the defaults object ...

  19. javascript

    i would initialize an AxiosRequestConfig[1] obj, and set the data in it to what you want to pass in the request.body-then pass the config to the delete method like so: