Bird
Raised Fist0
Vueframework~20 mins

Axios setup and configuration in Vue - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Axios Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when Axios is configured with a base URL?

Consider a Vue component that uses Axios with a base URL set. What will be the full request URL when making a GET request to '/users'?

Vue
import axios from 'axios';

const apiClient = axios.create({
  baseURL: 'https://api.example.com/v1'
});

export default {
  methods: {
    fetchUsers() {
      return apiClient.get('/users');
    }
  }
};
AThe request URL will be 'https://api.example.com/v1//users' with a double slash.
BThe request URL will be '/users' only, ignoring the base URL.
CThe request URL will be 'https://api.example.com/users', missing the '/v1' segment.
DThe request URL will be 'https://api.example.com/v1/users'.
Attempts:
2 left
💡 Hint

Think about how Axios combines the base URL with the request path.

📝 Syntax
intermediate
1:30remaining
Which Axios configuration option sets a timeout for requests?

Identify the correct Axios configuration option to set a request timeout of 5000 milliseconds.

A{ timeout: 5000 }
B{ time: 5000 }
C{ delay: 5000 }
D{ wait: 5000 }
Attempts:
2 left
💡 Hint

Look for the option that controls how long Axios waits before aborting a request.

🔧 Debug
advanced
2:30remaining
Why does this Axios request fail with a CORS error?

Examine the Axios request code below. Why might it cause a CORS error in the browser?

Vue
import axios from 'axios';

axios.get('https://api.example.com/data', {
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer token123'
  }
}).then(response => {
  console.log(response.data);
}).catch(error => {
  console.error(error);
});
AThe 'mode' option is not valid in Axios and does not affect CORS, causing the error.
BAxios automatically disables CORS, so the error is unrelated to this code.
CThe 'Content-Type' header must be 'text/plain' to avoid CORS errors.
DThe 'Authorization' header is missing, causing the server to reject the request.
Attempts:
2 left
💡 Hint

Check which options Axios supports and how CORS is handled in browsers.

❓ state_output
advanced
2:00remaining
What is the value of 'responseData' after this Axios call?

Given the following Vue component method using Axios, what will be the value of this.responseData after the call?

Vue
import axios from 'axios';

export default {
  data() {
    return { responseData: null };
  },
  methods: {
    async loadData() {
      try {
        const response = await axios.get('https://api.example.com/items');
        this.responseData = response.data.items;
      } catch (error) {
        this.responseData = [];
      }
    }
  }
};
AThe entire Axios response object including headers and status.
BNull, because the assignment is asynchronous and not awaited.
CAn array of items from the server response, or an empty array if the request fails.
DUndefined, since 'responseData' is not initialized in data().
Attempts:
2 left
💡 Hint

Consider what response.data.items represents and how errors are handled.

🧠 Conceptual
expert
3:00remaining
Which Axios interceptor setup correctly logs request URLs before sending?

Choose the correct way to add a request interceptor in Axios that logs the request URL before the request is sent.

Aaxios.use.interceptors.request(config => { console.log(config.url); return config; });
Baxios.interceptors.request.use(config => { console.log(config.url); return config; });
Caxios.request.interceptors.use(config => { console.log(config.url); return config; });
Daxios.interceptors.use('request', config => { console.log(config.url); return config; });
Attempts:
2 left
💡 Hint

Recall the correct Axios interceptor syntax for requests.

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

  1. Step 1: Understand axios.create()

    This method creates a new Axios instance that can have its own configuration like baseURL, headers, and timeout.
  2. Step 2: Purpose in Vue projects

    Using axios.create() helps keep your API calls consistent and reusable across components by sharing the same settings.
  3. Final Answer:

    To create a reusable Axios client with custom settings -> Option C
  4. 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

  1. Step 1: Check axios.create() syntax

    axios.create() accepts an object with configuration keys like baseURL, timeout, and headers.
  2. Step 2: Identify correct baseURL usage

    The correct key for setting the base URL is baseURL inside the config object.
  3. Final Answer:

    const api = axios.create({ baseURL: 'https://api.example.com' }) -> Option D
  4. Quick Check:

    baseURL inside object = const api = axios.create({ baseURL: 'https://api.example.com' }) [OK]
Hint: Use an object with baseURL key inside axios.create() [OK]
Common Mistakes:
  • Passing baseURL as a separate argument
  • Using url instead of baseURL
  • Passing a string directly without an object
3. Given this Axios instance setup in a Vue component:
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?
medium
A. The request will timeout and log an error message
B. The request will succeed and log the user data
C. The request will retry automatically until success
D. The request will hang indefinitely without error

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    The request will timeout and log an error message -> Option A
  4. Quick Check:

    Timeout 1s > 2s response = error [OK]
Hint: Timeout shorter than response time causes error [OK]
Common Mistakes:
  • Assuming Axios retries automatically
  • Thinking the request will succeed despite timeout
  • Ignoring the catch block handling
4. Identify the error in this Axios setup code inside a Vue component:
const api = axios.create({
  baseURL: 'https://api.example.com',
  timeout: '5000',
  headers: { 'Content-Type': 'application/json' }
});
medium
A. timeout should be a number, not a string
B. baseURL must be inside headers object
C. Content-Type header is invalid here
D. axios.create() cannot have headers property

Solution

  1. Step 1: Check timeout data type

    Timeout expects a number representing milliseconds, but here it is a string '5000'.
  2. Step 2: Validate other properties

    baseURL is correctly placed, and headers with Content-Type is valid for axios.create().
  3. Final Answer:

    timeout should be a number, not a string -> Option A
  4. 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

  1. 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.
  2. 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.
  3. 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.
  4. Final Answer:

    Use an interceptor to add Authorization header dynamically before each request -> Option B
  5. Quick 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]
Hint: Use request interceptor to add fresh token each time [OK]
Common Mistakes:
  • Setting headers once at creation, ignoring token updates
  • Accessing localStorage.token instead of getItem()
  • Not returning config in interceptor
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard