Common basic usage of axios in vue projects for beginners

We use Vue.js framework to develop front-end projects, will often send ajax requests server-side interface, in the development process, need to further encapsulate the axios to facilitate the use in our project.

1. About Axios

Axios framework full name (ajax – I/O – system)

A promise-based http client for browsers and node.js, so you can use the Promise API

What does axios do?
When we talk about axios, we have to talk about Ajax. In the old browser page when requesting data from the server, because the returned data is the whole page, the page will be forced to refresh a little, which is not very friendly for the user. And we only need to refresh part of the page data, but the data sent from the server side is the whole page data, very consuming network resources. And we only need to modify part of the page data, but also want to not refresh the page, so the asynchronous request is born!

Ajax(Asynchronous JavaScript and XML): Asynchronous web requests. Ajax enables pages to request data without refreshing

Axios is not a new technology, but essentially a wrapper around the native XMLHttpRequest, which can be used in browsers and HTTP clients for nodejs, and it is just Promise-based and conforms to the latest ES specification. It has the following features:

  • Create an XMLHttpRequest request in the browser
  • Sending http requests in node.js
  • Support Promise API
  • Support for interception of requests and responses
  • Conversion of request and response data
  • Cancel a request
  • Automatic decode JSON data
  • Client-side support to prevent CSRF/XSRF (cross-domain request forgery)

2. How to installation and use

There are 3 methods to install Axios:

1. npm install axios  // Installation via npm

2. bower install axios  // Installation via bower

3. <script src="https://unpkg.com/axios/dist/axios.min.js"></script>  // Installation via script tag

Import axios in the main.js file of the vue project

import axios from 'axios'
Vue.prototype.$axios = axios

Using axios in components

<script>
	export default {
		mounted(){
			this.$axios.get('/a/b').then(res=>{
				console.log(res);
			})
		}
	}
</script>

Axios request method

Axios supports all common http request methods:

  • get: get the data, request the specified information, return the entity object.
  • post: submits data to the specified resource (e.g. form submission or file upload)
  • put: update data, the data transmitted from the client to the server replaces the content of the specified document
  • patch: update data, is a supplement to the put method, used to make local updates to known resources
  • delete: request the server to delete the specified data

Send a GET http request:

this.$axios.get('/a/b',{
		params: {
				id:1
		}
}).then(res => {
		console.log(res.data);
	}, err => {
		console.log(err);
})

// or 

this.$axios({
	method: 'get',
	url: '/a/b',
		params: {
				id:1
		}
}).then(res => {
	console.log(res.data);
},err => {
	console.log(err);
})

Send a get POST request:

There are two general types of post requests:

  • form-data: form submission, image upload, file upload etc.
  • application/json: generally Used for ajax asynchronous requests.
// send form-data post request
const data = {
	a: "b", 
	c: "d",
}

let formdata = new FormData();
for(let key in data){
	formdata.append(key,data[key]);
}

this.$axios.post('/a/b',formdata).then(res => {
	console.log(res.data);
}, err => {
	console.log(err);
})





// send application/json post request
this.$axios.post('/a/b',{
	id:1
}).then(res => {
	console.log(res.data);
}, err => {
	console.log(err);
})

// or
$axios({
	method: 'post',
	url: '/a/b',
	data: {
		id:1
	}
}).then(res => {
	console.log(res.data);
}, err => {
	console.log(err);
})

Send a get PUT/PATCH request:

// put request
this.$axios.put('/a/b',{
	id:1
}).then(res => {
	console.log(res.data);
})

// patch request
this.$axios.patch('/a/b',{
	id:1
}).then(res => {
	console.log(res.data);
})

Send a get PUT/PATCH request:

this.$axios.delete('/a/b',{
	data: {
		id:1
	}
}).then(res => {
	console.log(res.data);
})

Send concurrent requests:

this.$axios.all([
	this.$axios.get('/a/b'),
	this.$axios.get('/c/d')
]).then(
	this.$axios.spread((abResult, cdResult)=>{
		console.log(abResult);
		console.log(cdResult);
	})
)

3. Creating Axios Instances

Sample Code:

let instance = this.$axios.create({
	baseURL: 'https://abc.com',
	timeout: 2000
})

instance.get('/a/b').then(res => {
	console.log(res.data);
})

The following are some common configurations for axios instances:

namedescriptiontype
baseURL Requested domain name, base addressString
timeout Request Timeout DurationNumber(ms)
url Request PathString
method Request methodString
headers Request headerObject
params Request parameters, stitching them to the URLObject
dataRequest parameters, put the parameters into the request bodyObject

The priority of the configuration is: Request Configuration > Instance Configuration > Global Configuration

4. Axios interceptor

Request interceptor sample code:

this.$axios.interceptors.request.use(config => {
	// before the request is sent

	return config
}, err => {
	// request error handler

	return Promise.reject(err);
})

// Or create an interceptor with an axios instance
let instance = $axios.create();
instance.interceptors.request.use(config => {
	return config;
})

Response interceptor sample code:

this.$axios.interceptors.response.use(res => {
	// do something to the response after request obtaining the data successfully

	return res // This return object will be passed to the response object of the request method
},err => {
	// do some to the error

	return Promise.reject(err);
})

5. Cancel Request

let source = this.$axios.CancelToken.source();

this.$axios.get('/a/b',{
	cancelToken: source
}).then(res => {
	console.log(res)
}).catch(err => {
	// This method will be executed when the request is cancelled
	console.log(err)
})

6. Error Handling

this.$axios.get(‘/a/b’).then(res => {

  // do somethind

}).catch(err => {

  // When the request interceptor and response interceptor throw errors, the err object returned is passed to the err object of the current function

  console.log(err);

})

RSS