Axios get in url works but with second parameter as object it doesn’t

Using Axios to Make GET Requests with URL Parameters

When using Axios, you may encounter a situation where making a GET request with URL parameters works fine when passed as part of the URL itself, but fails when passed as the second parameter as an object. In this blog post, we will explore this issue and provide solutions to overcome it.

The Problem

Let’s say you have a simple GET request using Axios:

axios.get('/api/data?param1=value1¶m2=value2')

This works perfectly fine and sends the URL parameters along with the request. However, when you try to pass the parameters as an object, like this:

axios.get('/api/data', { params: { param1: 'value1', param2: 'value2' } })

You might expect the same result, but unfortunately, it doesn’t work as expected. The parameters are not appended to the URL, and the request is sent without them.

Solution 1: Using the “params” Property

To pass URL parameters as an object using Axios, you need to use the “params” property of the Axios configuration object. Here’s how you can modify your code:

axios.get('/api/data', { params: { param1: 'value1', param2: 'value2' } })

This solution explicitly tells Axios to include the parameters in the request URL.

Solution 2: Using the “URLSearchParams” Class

If you prefer a more explicit approach, you can use the “URLSearchParams” class to construct the URL parameters and append them to the request URL. Here’s how you can achieve this:

const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');

axios.get('/api/data?' + params.toString())

This solution constructs the URL parameters manually and appends them to the request URL using the “toString()” method of the “URLSearchParams” class.

Conclusion

When making GET requests with URL parameters using Axios, it is important to use the correct syntax to ensure the parameters are included in the request. By either using the “params” property or the “URLSearchParams” class, you can successfully pass URL parameters as an object and retrieve the desired data.

Remember, the key is to be aware of how Axios handles URL parameters and choose the appropriate solution based on your specific use case.

Happy coding!


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *