Vue HTTP Requests

🌐 Vue HTTP Requests (API Calls)

In Vue.js, HTTP requests are used to communicate with backend servers or APIs to:
  • Fetch data (GET)

  • Send data (POST)

  • Update data (PUT / PATCH)

  • Delete data (DELETE)

Vue itself does not include an HTTP library, so we commonly use:

  • Axios (most popular)

  • Browser Fetch API


 Where to Make HTTP Requests in Vue?

Best places:

  • mounted() lifecycle hook

  • created() lifecycle hook

  • watch (when reacting to data changes)

  • Methods (on button click, form submit)


 Using Axios in Vue (Recommended ✅)

📦 Install Axios

npm install axios

Basic GET Request

<script>
import axios from 'axios'

export default {
data() {
return {
users: [],
loading: false
}
},
async mounted() {
this.loading = true
const response = await axios.get('https://jsonplaceholder.typicode.com/users')
this.users = response.data
this.loading = false
}
}
</script>

<ul>
<li v-for="user in users" :key="user.id">
{{ user.name }}
</li>
</ul>

POST Request (Send Data)

axios.post('https://api.example.com/users', {
name: 'Sanjit',
email: 'sanjit@mail.com'
})

With async/await:

async submitForm() {
try {
await axios.post('/users', this.form)
alert('User created')
} catch (error) {
console.error(error)
}
}

PUT / PATCH Request (Update Data)

axios.put(/users/${id}, {
name: 'Updated Name'
})
axios.patch(/users/${id}, {
status: 'active'
})

 DELETE Request

axios.delete(/users/${id})

 Handling Errors

try {
const res = await axios.get('/users')
} catch (error) {
console.error(error.response?.data)
}

✔ Always handle errors
✔ Show user-friendly messages


Using Fetch API (Alternative)

async mounted() {
const res = await fetch('https://jsonplaceholder.typicode.com/posts')
this.posts = await res.json()
}

📌 Axios is preferred because:

  • Automatic JSON parsing

  • Better error handling

  • Interceptors support


HTTP Requests with Methods (Button Click)

<button @click="loadData">Load Data</button>
methods: {
async loadData() {
const res = await axios.get('/data')
this.data = res.data
}
}

 HTTP Requests with Watchers

watch: {
search(newValue) {
this.fetchResults(newValue)
}
}

✔ Great for search & filters


 Axios Global Configuration (Best Practice)

axios.defaults.baseURL = 'https://api.example.com'
axios.defaults.headers.common['Authorization'] = 'Bearer token'

Or create instance:

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

 API Service Pattern (Scalable Apps)

// services/userService.js
import axios from 'axios'

export const getUsers = () => axios.get('/users')

✔ Keeps components clean
✔ Easy to maintain


Loading & UI States

<p v-if="loading">Loading...</p>
<p v-if="error">Something went wrong</p>

✔ Essential for good UX


 Common Mistakes ❌

❌ API calls inside computed properties
❌ No error handling
❌ Direct API calls everywhere
❌ Not canceling unnecessary requests


 Best Practices ✅

✔ Use Axios
✔ Centralize API logic
✔ Handle loading & error states
✔ Use async/await
✔ Secure tokens properly


 Summary Table

Task Method
Fetch data axios.get()
Send data axios.post()
Update data put() / patch()
Delete data axios.delete()
Best hook mounted()
Large apps API service layer

🏁 Conclusion

HTTP requests are the bridge between your Vue frontend and backend APIs.
Mastering Axios + proper architecture is crucial for real-world Vue applications.

You may also like...