Axios Get With Params

Posted on  by admin

Customizing Serialization

Modified4 years, 5 months ago. I want to put multiple same key in params and send GET request in axios to server. In backend, it requires

I am using axios and it uses JS object to send the request params. And obviously such object can't have multiple fields with the same key. How to put multiple same key in params? Nayeon KimNayeon Kim. You can send params like this:.

axios will build url like this /api_new?not[]=github¬[]=twitter&limit=10. axios auto add [] at the end of the list type params name. see more in this issues

The code must send get request:"",but it just ignored "params",help pls.

Not the answer you're looking for? Browse other questions tagged node.jsapimongooseaxios or ask your own question.

  • MrFox is a new contributor to this site.
  • Take care in asking for clarification, commenting, and answering.
  • Check out our Code of Conduct.

Not the answer you're looking for? Browse other questions tagged parametersgetaxios or ask your own question.

Search should be part of the URL and params should be passed as an object. 11 gold badge1111 silver badges3535 bronze badges.

3535 bronze badges. Modified1 year, 4 months ago. I am sending a get request to API with axios , but unable to acess the passed parametrs in that request.

Here is my code:API request. Request handling. Routing is working properly when there is no parameters given. console.log(req.params.category); is giving output as undefined.

Hope you got the Problem.. I believe what you are trying to do has got nothing to do with Axios,To get query parameters, in the server side of your code, you need to use the property query of the request, like this:. 11 gold badge2323 silver badges3030 bronze badges.

More Axios Tutorials

3030 bronze badges. params in Axios are URL parameters that become a querystring. params in Express' request object are route parameters. For example: When I define a URL such as /students/:id then req.params for GET /students/value will be {id: "value"}.

The options Parameter

What you are looking for in Express handler is req.query [docs]. The easiest way to make a GET request with Axios is theaxios.get() function.

The 2nd parameter to axios.get() is the Axios options: Axios will serializeoptions.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 aninstance of the JavaScript's built-in URLSearchParams class.

Axios's built-in query string serializer respects the toJSON() function, so it automatically serializes built-in custom JSONserialization, like Moment objectsor Mongoose documents. However, if you need more flexibility in how Axios serializes query strings, Axios supports a paramsSerializeroption that lets you overwrite the function Axios to serialize.

The easiest way to make a GET request with Axios is theaxios.get() function.

The first parameter to axios.get() is the URL. For example, below is how you make a GET requestto the URL

The 2nd parameter to axios.get() is the Axios options.For example, you don't have to serialize the query string ?answer=42 yourself. Axios will serializeoptions.params and add it to the query string for you.

Not the answer you're looking for? Browse other questions tagged javascriptvue.jsaxios or ask your own question.

The below request is equivalent:. The options parameter is also how you set any request headers. For example,below is how you set the Test-Header header on a GET request. Modified3 years, 7 months ago. I create one get request with axios:.

but my result is an array [123asdas1,asdasd2312] and when the axios excute the request he create that url:.

so It's possible to remove the [] from q param? 1313 gold badges4141 silver badges6868 bronze badges.

6868 bronze badges. When composing a query string where one field has multiple values (i.e.

if it were an array), then there is no standard that says how it must be encoded in the query string, however most web servers accept this syntax:.

which is why axios defaults to it. Check your web server to see if it is reading the parameter as an array correctly.

If you want to force it to be encoded in some other way, just convert the array to a string in whatever format you want and send it as a single value:.

(The [ and ] characters may be percent-encoded.). In general, this syntax cannot distinguish between the string "[value1,value2]" and the array [value1, value2], so the web server will have to choose one or the other.

Not the answer you're looking for? Browse other questions tagged javascriptpromiseaxios or ask your own question.

Again, this is all dependent on your web server. 88 gold badges7070 silver badges9191 bronze badges.

9191 bronze badges. Modified1 year, 7 months ago. I am trying to implement getting data from API with params. I got two functions for that and I can't see the error. I received working solutions with the code below, so the problem probably with the second parameter.

It's not clear about what you are trying to accomplish but I think your functions should be like this:. Using Async/Await:.

Using Promises:. Do note the name parameter which I am passing to getFilteredProducts method. Previously this wasn't there so String(name) would result in an empty string "".

22 gold badges1414 silver badges3131 bronze badges.

3131 bronze badges.

Axios also provides shorthand methods for performing different requests, like so:

Here, you pass a request object with the necessary configuration of the request as the argument to the axios.get() method. While there are several options that you can pass to this request object, here are the most common and popular ones:

  • baseUrl – When specified, this baseUrl is prepended to url unless the url is absolute
  • headers – An object with custom headers to be sent with the requestor, like headers: {'X-Requested-With': 'XMLHttpRequest'},
  • params – An object whose key/value pairs are appended to the url as query strings
  • auth – An object with a username and password to authenticate an HTTP Basic auth request

The above Axios request can be rewritten as the following:

This object must include the url property to fetch the data. Requests default to the GET request when the method property is not specified.

You can also pass a responseType option, which indicates the type of data that will be returned by the server to the request config object (set to json by default).

For example, you can rewrite the above code like so:

The responseType option can be set to arraybuffer, document, blob, text, or stream. It is essential to set the responseType option when the returned response or data is not in JSON format.

For example, the following code fetches a nature image from Unsplash as a Node stream. You can then use the createWriteStream() of the inbuilt fs module and write the fetched stream in a file.

The following code creates a file named nature.jpg in your project folder:

You can also use the popular async/await instead of promises. For example, you can rewrite the above code by placing it inside an async function:

Finally, you can get the data from the response body using destructuring assignments:

How to make Axios GET requests with query parameters

In this section, we will learn how to make Axios GET requests with query parameters.

First, add the following code to the index.js file:

In the code above, we use the URLSearchParams method from the url module to convert an object with query parameters as key/value pairs in the required URL query format.

Here is what the params will look like:

And here is what the returned data looks like:

How to make Axios GET requests with an API key

One often needs to authenticate requests by passing an API key along with the request. In this section, we will learn how to use an API key with Axios to make requests. We will use the NASA API as an example.

First, navigate to in the browser and fill the required fields to generate an API key.

Click on the Signup button. On the next page, your API key will be shown to you.

The API keys should be kept hidden from the public and stored as environment variables inside a .env file. dotenv is a popular npm library used to load environment variables from the .env file.

Run the following command to install the dotenv package:

Next, create a new file named .env by running the following command:

Paste the NASA API key into the .env file as shown below:

Now, add the following code to the index.js file to fetch data from the NASA API:

In the above code, we import the dotenv package and use the API key in the URL as a query parameter.

You will need to restart your application, so hit CTRL+C in the terminal and run the command npm run dev to start the Node application.

You will see a response similar to this from the NASA API:

You can also use the params option of the request config to make the same request:

You can also authenticate requests with other HTTP authentication methods like Bearer authentication by passing the Bearer Token in the Authorization header. For example:

How to make concurrent requests with Axios

You may need to make concurrent requests to multiple endpoints. In this section, we will learn how you can use the axios.all() method to make multiple requests

To begin, add the following code to the index.js file:

Here, we pass an array of axios.get() requests in the axios.all() method, then map over the endpoints array to create an array of axios.get() requests, which is then resolved by the axios.all() method.

The response order is the same as the order of the requests in the axios.all() method:

Error handling in Axios

In this section, we will discuss how to handle errors with Axios. The most common way is to chain a .catch() method with the axios.get() to catch any errors that may occur.

Add the following code to the index.js file:

In the code above, we are trying to fetch a character from The Rick and Morty API whose id is -1, and because there is no such character with a negative id, this request will result in an error.

The above catch block consoles any error that may occur. This error object is quite large, and you may not always display everything, so you can be selective about what to log to the error message.

You can also handle errors based on their types. Add the following code to the index.js file:

If the error occurred on the server side, then the error object will contain a response property that can be used to access the error’s status, headers, and other details.

If the request was made and no response was received, then the error object will contain the request property XMLHttpRequest in the browser, and an instance of http.ClientRequest in Node.

If an error occurred while making the request, then error.message will indicate such errors.

Because the error in the above code occurred on the server side, the error object will have a response property, and the following message will be seen in the terminal:

You can also throw an error by using the validateStatus request config option. For example:

This option will throw an error when the response’s status satisfies the condition in it. You will see a message similar to this in the terminal:

How to make HEAD requests with Axios

A HEAD request is a GET request without a message body. You can create a HEAD request with the axios.head method. The data property in the response object will be empty with such requests.

For example:

Here is the message you will see in the terminal:


In this article, we discussed what Axios is and how can you use it to make GET requests. We also learned how to make concurrent requests, handle errors, and make HEAD requests.

LogRocket: Full visibility into your web apps

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page and mobile apps.

Try it for free.