# Axios
This section is based on the Axios package. Axios is a Promise based HTTP client. It's a JavaScript library used to make HTTP requests. I am using a Realtime Database from firebase.
# Installation via NPM
npm install --save axios
# POST
To post data with Axios, you just need to import it (line 14), and then use the POST method on Axios which takes two arguments, the url as a string where you send the data Here I am using a firebase url), where I am sending the second parameters the object I created (here 'name'). I am then catching the response or the error.
Of course the exact steps and the url, depend on the backend, on how you organize the data.
# Input:
<template>
<div>
<form>
<label for="name">Enter Employee Name: </label>
<input v-model="firstName" type="text" />
<input v-model="lastName" type="text" />
<p>Your name is: {{ firstName }} {{ lastName }}</p>
<button @click.prevent="submitted">Send</button>
</form>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
firstName: 'Pam',
lastName: 'Beesly'
}
},
methods: {
submitted() {
const name = {
firstName: this.firstName,
lastName: this.lastName
}
axios
.post('https://vue-axios-8cb49.firebaseio.com/employees.json', name)
.then(res => console.log(res))
.catch(error => console.log(error))
}
}
}
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# Output:
# GET
To get data with axios, you need to import it. (line 6), and then use the GET method on Axios which take at least one argument, the url as a string where the data is retrieved from. Here I am using a firebase url. Here I am receiving a object as a response which contain a list of users that I am loop though to assign an id and extract the firstName
.
Of course the exact steps and the url, depend on the backend, on how the data is organized...
# Input:
<template>
<p>{{ firstName }}</p>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
firstName: ''
}
},
created() {
axios
.get('https://vue-axios-8cb49.firebaseio.com/employees.json')
.then(res => {
console.log(res)
const data = res.data
const users = []
for (let key in data) {
const user = data[key]
user.id = key
users.push(user)
}
console.log(users)
this.firstName = users[0].firstName
})
.catch(error => console.log(error))
}
}
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# Output:
Pam
# Setting a global request configuration
You can set up a baseURL for Axios. It is convenient because:
- You can just refer to it in the components where it is used and
- You don't have to change it everywhere whenever you need to use a different one.
In the main.js file, you need to import Axios and just set the baseURL using the defaults
method on 'axios'.
import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'
Vue.config.productionTip = false
axios.defaults.baseURL = 'https://vue-axios-8cb49.firebaseio.com'
new Vue({
render: h => h(App)
}).$mount('#app')
2
3
4
5
6
7
8
9
10
11
You can now delete that part of the link from the components. For the Post example above, the following line:
axios.post('https://vue-axios-8cb49.firebaseio.com/employees.json', name)
is now
axios.post('/employees.json', name)
# Adding headers configuration
You can add global header configuration on several specifications or targets.
On common
, used for any requests, no matter which type it is, you can specify your own header by adding a property. For example, here, I am adding a random Authorization header ( Line )
You can also target the GET request only. For example here, I am forcing all GET request to only accept JSON.
import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'
Vue.config.productionTip = false
axios.defaults.baseURL = 'https://vue-axios-8cb49.firebaseio.com'
axios.defaults.headers.common['Authorization'] = 'myCuteAuthorization'
axios.defaults.headers.get['Accepts'] = 'application/json'
new Vue({
render: h => h(App)
}).$mount('#app')
2
3
4
5
6
7
8
9
10
11
12
13
Visit the Axios Github repository, for more info on the Axios configuration options
# Using Axios Interceptors
Interceptors are functions you can define which intercept that get triggered on each request and each response that reaches it, before they are handled by then or catch.
import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'
Vue.config.productionTip = false
axios.defaults.baseURL = 'https://vue-axios-8cb49.firebaseio.com'
// Add a request interceptor
axios.interceptors.request.use(
function(config) {
// Do something before request is sent
console.log('Sending request')
console.log(config)
return config
},
function(error) {
// Do something with request error
console.log('Error incoming')
console.log(error)
return Promise.reject(error)
}
)
// Add a response interceptor
axios.interceptors.response.use(
function(response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response
},
function(error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error)
}
)
new Vue({
render: h => h(App)
}).$mount('#app')
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
You can also remove those interceptors by using eject
.
# Custom Axios Instances.
In the case where you want several Axios instances. For instance, if you want to use several baseURL or use a specific header somewhere. You can customize those instances. Here I am creating a new file axios-auth.js
where I will set up a random custom header. You don't need to create a new file but here I will.
Create a file axios-auth.js
in src folder.
touch src/axios-auth.js
You can now customize that instance and export it to be used anywhere.
import axios from 'axios'
const instance = axios.create({
baseURL: 'https://vue-axios-8cb49.firebaseio.com/employees.json'
})
instance.defaults.headers.common['SOMETHING'] = 'something'
export default instance
2
3
4
5
6
7
8
9
And in the component, you can now import this instead of axios as followed:
import axios from '../axios-auth';