What if you could save hours of repetitive coding by setting up your API calls just once?
Why Axios setup and configuration in Vue? - Purpose & Use Cases
Imagine you have to fetch data from multiple websites in your Vue app, and for each request, you write the full URL, headers, and error handling every single time.
Manually writing the same setup for every request is tiring, easy to forget, and leads to inconsistent code that is hard to maintain or update.
Axios setup and configuration lets you define common settings once, so every request automatically uses them, making your code cleaner and easier to manage.
fetch('https://api.example.com/data', { headers: { 'Authorization': 'token' } }).then(...).catch(...)
const api = axios.create({ baseURL: 'https://api.example.com', headers: { 'Authorization': 'token' } }); api.get('/data').then(...).catch(...)It enables you to write fewer lines of code while keeping your API calls consistent and easy to update.
When building a weather app, you can set the base URL and API key once, then simply call different endpoints without repeating setup.
Manual API calls are repetitive and error-prone.
Axios configuration centralizes settings for all requests.
This leads to cleaner, more maintainable Vue code.
Practice
axios.create() in a Vue project?Solution
Step 1: Understand axios.create()
This method creates a new Axios instance that can have its own configuration like baseURL, headers, and timeout.Step 2: Purpose in Vue projects
Using axios.create() helps keep your API calls consistent and reusable across components by sharing the same settings.Final Answer:
To create a reusable Axios client with custom settings -> Option CQuick Check:
axios.create() = reusable client [OK]
- Thinking axios.create() fetches data automatically
- Confusing axios.create() with Vue lifecycle hooks
- Assuming axios.create() changes Vue's reactivity
Solution
Step 1: Check axios.create() syntax
axios.create() accepts an object with configuration keys like baseURL, timeout, and headers.Step 2: Identify correct baseURL usage
The correct key for setting the base URL is baseURL inside the config object.Final Answer:
const api = axios.create({ baseURL: 'https://api.example.com' }) -> Option DQuick Check:
baseURL inside object = const api = axios.create({ baseURL: 'https://api.example.com' }) [OK]
- Passing baseURL as a separate argument
- Using url instead of baseURL
- Passing a string directly without an object
const api = axios.create({ baseURL: 'https://api.example.com', timeout: 1000 });
api.get('/users')
.then(response => console.log(response.data))
.catch(error => console.log('Error:', error.message));What will happen if the server takes 2 seconds to respond?
Solution
Step 1: Understand timeout setting
The timeout is set to 1000 milliseconds (1 second), so if the server takes longer, Axios will abort the request.Step 2: Effect on slow response
Since the server takes 2 seconds, which is longer than 1 second, Axios triggers a timeout error and the catch block runs.Final Answer:
The request will timeout and log an error message -> Option AQuick Check:
Timeout 1s > 2s response = error [OK]
- Assuming Axios retries automatically
- Thinking the request will succeed despite timeout
- Ignoring the catch block handling
const api = axios.create({
baseURL: 'https://api.example.com',
timeout: '5000',
headers: { 'Content-Type': 'application/json' }
});Solution
Step 1: Check timeout data type
Timeout expects a number representing milliseconds, but here it is a string '5000'.Step 2: Validate other properties
baseURL is correctly placed, and headers with Content-Type is valid for axios.create().Final Answer:
timeout should be a number, not a string -> Option AQuick Check:
timeout must be number, not string [OK]
- Putting baseURL inside headers
- Removing headers property
- Using string for timeout value
Solution
Step 1: Understand token dynamic retrieval
The token in localStorage can change, so it should be read fresh before each request, not just once at setup.Step 2: Use Axios interceptor for dynamic headers
Using an interceptor lets you add or update headers before every request, ensuring the latest token is used.Step 3: Evaluate options
const api = axios.create({ baseURL: 'https://api.example.com' }); api.interceptors.request.use(config => { config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`; return config; }); uses an interceptor to set Authorization header dynamically. Options A and C set it once at creation, which may become stale. const api = axios.create({ baseURL: 'https://api.example.com', headers: { Authorization: localStorage.token } }); uses incorrect localStorage access.Final Answer:
Use an interceptor to add Authorization header dynamically before each request -> Option BQuick Check:
Interceptor for dynamic token = const api = axios.create({ baseURL: 'https://api.example.com' }); api.interceptors.request.use(config => { config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`; return config; }); [OK]
- Setting headers once at creation, ignoring token updates
- Accessing localStorage.token instead of getItem()
- Not returning config in interceptor
Ready to prove it?
Pass the test and this pattern moves unknown
