I'm using Axios in my VueJS application and I want to add a default GET param in my request. I send my API-KEY through the URL ?api-key=secret
and I don't want to specify this parameter each time.
I see in the documentation that we can set Global custom defaults. With that we don't have to specify the header each time. But can we do the same for get param ?
axios. defaults. baseURL = 'https://api.example.com'; axios.
In this article, you are going to learn about how to use query params with the Axios Get request. In general, query parameters refer to the defined set of parameters that are attached to the end of an URL. With the help of the query parameter, one can perform a specific task by defining specific content or action.
Instead of adding the headers to each request, you can put them as default headers, and they will apply to all the requests. To do so, use the defaults. headers property of the axios object. This snippet will add the x-rapidapi-key header to all the requests.
I struggled to get this to work with axios instances using the two most commonly suggested methods:
// method 1: setting axios.defaults.params at the class level
axios.defaults.params = {}
axios.defaults.params['api-key'] = secret
and
// method 2: setting the `params` attribute at an instance level
const axClient = axios.create({
baseURL: process.env.VUE_APP_BASE_URL,
params: {
api-key: process.env.VUE_APP_API_KEY
}
});
I did however, manage to get it working nicely using interceptors like this:
// create an instance with default properties
const axClient = axios.create({
baseURL: process.env.VUE_APP_BASE_URL,
});
axClient.interceptors.request.use((config) => {
// use config.params if it has been set
config.params = config.params || {};
// add any client instance specific params to config
config.params['api-key'] = process.env.VUE_APP_API_KEY;
return config;
});
The benefit of this approach is that the instance level params can be dynamic/computed per request if needed.
As a (slightly contrived) example, if you needed to add a JWT to each request (including any logic to fetch it from your storage method of choice) and even react to the logic around that. So in this toy example, if the user doesn't have a JWT in storage, redirect them to the login page instead of making the request.
Here it is:
axios.defaults.params = {}
axios.defaults.params['api-key'] = secret
If you need to call a function before each axios request, you should use an interceptor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With