Source code analysis from xhr to axios (two)

1. Understanding and use of axios

    In our daily development, everyone should more or less involve using axios to send requests, especially the vue framework, because the main push of vue to send requests is to use axios for interaction.
1. Axios features:
    (1) Promise- based ajax request library
    (2) Browser/node can be used
    (3) Support request/response interceptor
    (4) Support cancel request
    (5) Request/response data conversion
    (6) Send multiple requests in batch (promise.all)
2. The method of sending requests:
    axios.request(config)
    axios.get(url[, config])
    axios.delete(url[, config])
    axios.head( url[, config])
    axios.options(url[, config])
    axios.post(url[, data[, config]])
    axios.put(url[, data[, config]])
    axios.patch(url[ , data[, config]])
3.Interceptors

// Add a request interceptor
//请求拦截器发送请求之前执行
axios.interceptors.request.use(function (config) {
    
    
    // Do something before request is sent
    return config;
  }, function (error) {
    
    
    // Do something with request error
    return Promise.reject(error);
  });
  // Add a response interceptor
  //响应拦截器在得到响应数据之后执行
axios.interceptors.response.use(function (response) {
    
    
    // Do something with response data
    return response;
  }, function (error) {
    
    
    // Do something with response error
    return Promise.reject(error);
  });

4. Axios default configuration
axios.defaults.baseURL ='https://api.example.com'; the default request address
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post[' Content-Type'] ='application/x-www-form-urlencoded'; The default encoding method
5.axios.create()
Description: The second encapsulation of axios, why is the second encapsulation, because axios is the encapsulated xhr. So axios.create is equivalent to 2 encapsulation of xhr, not 2 encapsulation of axios.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>axios.create</title>
</head>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
  // axios.create(config)
  // (1)根据指定的配置创建一个新的axios
  // (2)新的axios没有取消请求和批量发送请求的方法,其他语法相同
  // (3)创建这个语法的原因:可能在一个项目中用到2个不同的服务器

  axios.default.baseURL = 'https://www.baidu.com'
  axios({
    
    
    url:'/get'//https://www.baidu.com/get
  })

  //当同一个项目用到2个不同的服务器地址的时候,不可能去修改default.baseURL
  const instance = axios.create({
    
    
   baseURL:'http://www.google.cn'
  })
  //用instance发送请求
  instance({
    
    
    url:'/get'//http://www.google.cn/get
  })
</script>

</html>

Guess you like

Origin blog.csdn.net/lbchenxy/article/details/105381631