📖 Scenario: You are building a Vue 3 app that needs to fetch user data from an API. To do this, you will set up Axios, a popular tool for making HTTP requests, and configure it properly.
🎯 Goal: Set up Axios in a Vue 3 project by creating a basic data structure, adding a base URL configuration, making a GET request to fetch user data, and completing the component setup.
📋 What You'll Learn
Create a reactive data variable to hold user data
Add an Axios instance with a base URL configuration
Use Axios to fetch user data from the API endpoint '/users'
Complete the Vue component setup with template and script
💡 Why This Matters
🌍 Real World
Setting up Axios in Vue is common for apps that need to get data from APIs, like user profiles, posts, or products.
💼 Career
Many frontend developer jobs require fetching and displaying data from APIs using Axios and Vue, so this skill is very practical.
Progress0 / 4 steps
1
DATA SETUP: Create reactive user data
In the <script setup> section, import ref from 'vue' and create a reactive variable called users initialized to an empty array [].
Vue
Hint
Use import { ref } from 'vue' and then const users = ref([]) to create reactive data.
2
CONFIGURATION: Create Axios instance with base URL
Import axios from 'axios' and create a constant called api using axios.create() with the base URL set to 'https://jsonplaceholder.typicode.com'.
Vue
Hint
Use axios.create() with an object that has baseURL set to the API URL.
3
CORE LOGIC: Fetch user data with Axios
Use the onMounted lifecycle hook from 'vue' to call api.get('/users') and assign the response data to users.value. Import onMounted from 'vue' as well.
Vue
Hint
Use onMounted with an async function that awaits api.get('/users') and sets users.value.
4
COMPLETION: Display user names in template
In the <template>, add an unordered list <ul> that uses v-for to loop over users and display each user's name inside a <li>. Use :key="user.id" for each <li>.
Vue
Hint
Use <ul> with v-for="user in users" and :key="user.id" to list user names.
Practice
(1/5)
1. What is the main purpose of using axios.create() in a Vue project?
easy
A. To convert Axios requests into Vue components
B. To automatically fetch data when the component mounts
C. To create a reusable Axios client with custom settings
D. To replace Vue's reactive system with Axios
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 C
Quick Check:
axios.create() = reusable client [OK]
Hint: Remember axios.create() makes a custom client [OK]
Common Mistakes:
Thinking axios.create() fetches data automatically
Confusing axios.create() with Vue lifecycle hooks
Assuming axios.create() changes Vue's reactivity
2. Which of the following is the correct way to set a base URL when creating an Axios instance?
easy
A. const api = axios.create('https://api.example.com')
B. const api = axios.create(baseURL = 'https://api.example.com')
C. const api = axios.create({ url: 'https://api.example.com' })
D. const api = axios.create({ baseURL: 'https://api.example.com' })
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 D
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 A
Quick Check:
timeout must be number, not string [OK]
Hint: Timeout must be numeric, not quoted string [OK]
Common Mistakes:
Putting baseURL inside headers
Removing headers property
Using string for timeout value
5. You want to create an Axios instance in Vue that automatically adds an Authorization header with a token stored in localStorage for every request. Which setup is correct?
hard
A. const api = axios.create({ baseURL: 'https://api.example.com' }); api.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('token')}`;
B. const api = axios.create({ baseURL: 'https://api.example.com' }); api.interceptors.request.use(config => { config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`; return config; });
C. const api = axios.create({ baseURL: 'https://api.example.com', headers: { Authorization: `Bearer ${localStorage.getItem('token')}` } });
D. const api = axios.create({ baseURL: 'https://api.example.com', headers: { Authorization: localStorage.token } });
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 B