Axios introduction and secondary packaging of axios

Table of contents

1. Axios basics

1. What is axios?

2. Axios installation

3. Axios common configuration items

4. The difference between axios and ajax 

2. Use axios to send requests

1. Send a get request without parameters

2. Send a get request with parameters

3. Send a post request without parameters

4. Send a post with a request

4.1 Send data in json format:

4.2 Send data in form format:

三、 then、catch、finally

4. Axios shortcut method

5. Axios instance

6. Global configuration of axios

Seven, axios interceptor

8. Axios concurrent requests

Nine, axios secondary packaging


1. Axios basics

1. What is axios?

Axios is a promise-based HTTP library that can be used in the browser and node.js. The axios mechanism is also encapsulated in jQuery, but only for browsers.

Axios features:

  • Send XMLHttpRequests request in browser

  • Send http request in node.js

  • Support Promise API

  • Intercept requests and responses

  • Transform request and response data

  • Automatically convert JSON data

2. Axios installation

use npm

npm install axios

use cdn

<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.js"></script>

3. Axios common configuration items

Only the url option is required, and the others are optional. Here are some commonly used configuration items. Axios has many other configuration items, which can be viewed on the axios official website .

axios({
	// 请求路径
	url:"",
	// 请求方式,默认发送get请求
	method:"",
	// get请求携带的参数写在params中
	params:{},
	// post请求携带的参数写在data中
	data:{},
	// 请求头
	headers:{},
	// 表示请求超过timeout时间没有响应就中断 (单位为毫秒)
	timeout:1000,
	// 规定后端返回的数据格式,默认值是json
	responseType: 'json'
})

Note: The default value of method is get, so methods can be omitted when sending a get request, and the default value of responseType is json 

4. The difference between axios and ajax 

Ajax features:
    1. Ajax is asynchronous XML and JavaScript 
    2. It can run on browsers but not on node.
    3. The data sent to the background needs to be manually converted, and the request header needs to be manually set.
    4. The data responded by the backend needs to be converted into js by itself Object format (the corresponding data in the background is in json format)
axios features:
    1. Axios is a promise-based http library
    2. You can call promise api
    3. Axios sends a get request by default, and the default format of the sent data is json
    4. The axios request header The data format will be converted automatically 

2. Use axios to send requests

1. Send a get request without parameters

axios({
  url:'请求地址'
})

2. Send a get request with parameters

When sending a get request with parameters, the parameters are spliced ​​into the url address in the format of a query string.

We put the parameters that the get request needs to carry into params, and axios will automatically convert them into query strings.

axios({
  url:'请求地址',
  // 将要传给后端的数据放到params中,axios会自动将它们转成查询字符串 (即 ?a=1&b=2)
  params:{
    a:1,
    b:2
  }
})

3. Send a post request without parameters

axios({
  url:'请求地址',
  method:'post'
})

4. Send a post with a request

4.1 Send data in json format:

The default data format sent by post request is json format

axios({
  url:"请求地址",
  method:"post",
  // 在请求头中指明发送的数据是json格式的数据,但是这里不写也可以,因为post请求默认发送的数据格式就是json 
  // headers:{
  //   "Content-Type":"application/json"
  // },
  data:{
    a:1,
    b:2
  }
})

4.2 Send data in form format:

Use the Qs tool to convert form format data into json format data, you need to introduce Qs first:

<script src="https://cdn.bootcdn.net/ajax/libs/qs/6.11.0/qs.js"></script>
axios({
  url:"请求地址",
  method:"post",
  // 在请求头中指明发送的数据是表单格式的数据,但是这里不写也可以,因为axios请求头的数据格式会自动转换 
  headers:{
    // "Content-Type":"application/x-www-form-urlencoded",
    // 如果需要token认证,可以在请求头中携带
    "Authorization":token
  },
  // 这里使用Qs将表单格式的数据转成json格式数据传给后台,因为后台需要接收json格式的数据
  data:Qs.stringify({
    a:1,
    b:2
  })
})

三、 then、catch、finally

Because axios is a promise-based HTTP library, it supports the promise api, and we can use then, catch, and finally methods in axios.

axios({
  url:"请求地址",
  method:"post",
  headers:{
    "Authorization":token
  },
  data:Qs.stringify({
    a:1,
    b:2
  })
}).then(res=>{
  console.log(res,'获取响应');
}).catch(err=>{
  console.log(err,'打印错误信息');
}).finally(()=>{
  console.log('最终执行');
})

4. Axios shortcut method

Axios provides the following shortcut methods: (the brackets indicate optional parameters, and the config configuration object is the same as axios)

axios.request(config)    --> equivalent to axios(config)

axios.get(url[, config])

axios.delete(url[, config])

axios.head(url[, config])

axios.options(url[, config])

axios.post(url[, data[, config]])  --> data indicates the parameters to be passed

axios.put(url[, data[, config]])

axios.patch(url[, data[, config]])

Get, delete, head, and options are used in the same way, and post, put, and patch are used in the same way.

(post and put: used to save multiple pieces of form data; patch: used to save one piece of form data)

// 1、get无参请求
axios.get('请求地址').then(res=>{
  console.log(res);
})

//----------------------------------------

// 2、get有参请求
let url = '请求地址'
axios.get(url,{
  params:{
    a:1,
    b:2
  },
  timeout:2000
}).then(res=>{
  console.log(res);
})

//----------------------------------------

// 3、post有参请求
// 3.1 json格式数据
let url = '请求地址'
let data = {
  a:1,
  b:2
}
axios.post(url,data).then(res=>{
  console.log(res);
})

//----------------------------------------

// 3.2 表单格式的数据
let url = '请求地址'
let data = {
  a:1,
  b:2
}
axios.post(url,Qs.stringify(data),{
  headers:{
    "Authorization":token
  }
}).then(res=>{
  console.log(res);
})

5. Axios instance

Create an axios instance:
axios.create([config])

// 创建实例
let instance = axios.create({
  baseURL: '基础路径',
  timeout: 2000,
  headers:{
    "Authorization": token
  }
})
// 使用实例
instance.post('除去基础路径后剩下的路径',{
  a:1,
  b:2
}).then(res=>{
  console.log(res);
})

6. Global configuration of axios

Globally configure axios default configuration items: add some default configuration items to all axios requests

axios.defaults.baseURL = '基础路径';
axios.defaults.headers.common['Authorization'] = token;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

Seven, axios interceptor

Axios provides us with two types of interceptors:

One is the request interceptor, which intercepts the request direction (successful request, failed request);

The other is the response interceptor, response direction (successful response, failure response)

The role of the interceptor: it is used to process the operation when we initiate a request or respond to a network request.

//请求拦截器 对所有的axios请求做一个拦截
axios.interceptors.request.use(
  config=>{
    // 在发送请求之前做些什么
    return config
  },
  error=>{
    // 对请求错误做些什么
    return Promise.reject(error)
  }
);

// 响应拦截器 对响应数据处理
axios.interceptor.response.use(
  response=>{
    // 对响应数据做点什么
    return response
  },
  error=>{
    // 对响应错误做点什么
    return Promise.reject(error)
  }
)

use:

When sending a request, if it is not a login interface and needs to carry a token, then we can perform corresponding operations in the request interceptor. The response interceptor is mainly used to extract the response data, because the response returned by the response interceptor is the data encapsulated by axios , and response.data is the response data returned by the backend.

//请求拦截器
axios.interceptors.request.use(
  config=>{
    // 在发送请求之前做些什么
    if(config.url!=='登录接口'){
      // 需要携带token 每一个请求请求头需要携带token
      config.headers.Authorization='token值';
    }
    return config
  },
  error=>{
    // 对请求错误做些什么
    return Promise.reject(error)
  }
);
// 响应拦截器
axios.interceptor.response.use(
  response=>{
    // 对响应数据做点什么
    // response.data才是后端返回的响应数据,response是axios封装后返回的数据
    let res = response.data;
    return res
  },
  error=>{
    // 对响应错误做点什么
    return Promise.reject(error)
  }
)

axios.post('请求地址',{
  a:1,
  b:2
}).then(res=>{
  console.log(res);
});

8. Axios concurrent requests

Using axios concurrent requests can send multiple asynchronous requests at one time.

Helper functions for handling concurrent requests:

axios.all(iterable)

axios.spread(callback)

axios.all([
	axios.get(),
	axios.get(),
	axios.post()
]).then(
	axios.spread((res1,res2,res3)=>{
		console.log(res1,res2,res3); //依次打印每一个响应
	})
)
axios.all([
	axios.get(),
	axios.get(),
	axios.post()
]).then(res=>{
	console.log(res) //打印一个数组,包含上述三个请求的响应结果
})

Nine, axios secondary packaging

We implement the secondary packaging of axios in the vue-cli scaffolding.

download axios

-S means install in production environment

cnpm i -S axios

Download Qs

cnpm i -S qs

Create a new folder utils under src, create a new file request.js under the utils folder 

 src/utils/request.js

import axios from 'axios'
import Qs from 'qs'
let qs = Qs

// 创建axios实例对象
let instance = axios.create({
  baseURL:"基础路径",
  timeout:5000
})

// 请求拦截器
instance.interceptors.request.use(config=>{
  // console.log(config,'请求配置项');
  if(config.url !== '登录接口'){
    config.headers.Authorization = 'token值'
  }
  return config
},error=>{
  alert('请求失败')
  return Promise.reject(error)
})

// 响应拦截器
instance.interceptors.response.use(response=>{
  let res = response.data
  return res
},error=>{
  return Promise.reject(error)
})

// 封装get方法并导出
export function get(url,params){
  return instance.get(url,{
    params,
  })
}
// 封装postJSON方法 (发送json格式数据)
export function postJSON(url,data){
  return instance.post(url,data)
}
// 封装post方法 (发送表单格式数据)
export function post(url,data){
  return instance.post(url,qs.stringify(data))
}

// 导出axios实例
export default instance

use:

src/views/AboutView.vue

 src/views/HomeView.vue 

Guess you like

Origin blog.csdn.net/lq313131/article/details/127173938