I'm using axios.create() to pass in a baseURL and some default query params like this
axios.create({
baseURL: 'http://somebigurlhere',
params: {
part: 'part',
maxResults: 5,
key: 'key'
}
});
When I use
axios.get('/search', {
params: {
q: 'word'
}
});
the default params do not get merged in the GET call.
What I get is
http://somebigurlhere/search?q=word
instead of
http://somebigurlhere/search?part=part&maxResults=5&key=key&q=asd
I tried putting the configuration in many other ways but it still doesn't work. Am i doing something wrong here ?
I tried the same in other projects and it is working there. Just created a new react app with create-react-app and this doesn't seem to work anymore.
POST should not have query param. You can implement the service to honor the query param, but this is against REST spec.
I solved it using 2 ways:
Using default params and spreading them when using the request
export const API_DEFAULT_PARAMS = {
part: 'part',
maxResults: 5,
key: 'key'
}
export default axios.create({
baseURL: 'http://somebigurlhere',
});
Then to use it:
import api, { API_DEFAULT_PARAMS } from './place/where/previous/file/is';
....
api.get('/search', {
params: {
// spread the default params
...API_DEFAULT_PARAMS,
// add your own parameters here
q: 'word',
}
});
Using interceptors as a user suggested here
const instance = axios.create({
baseURL: 'http://somebigurlhere',
});
instance.interceptors.request.use(config => {
config.params = {
// add your default ones
part: 'part',
maxResults: 5,
key: 'key',
// spread the request's params
...config.params,
};
return config;
});
export default instance;
Then to use it
import api from './place/where/previous/file/is';
...
api.get('/search', {
params: {
q: 'word',
}
});
I like the interceptor approach more because it abstracts the default params to the instance file itself and you don't have to import and spread an object every time you use the instance.
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