Detailed explanation of axios, basic usage and packaging

Axios Explain, Basic Use and Packaging

  • What is Axios
  • Comparison
    • 1. AJAX
    • 2. $.ajax Method for jQuery
    • 3. Axios
    • 4. XMLHttpRequest
    • 5. Fetch
    • 6. Summary
  • Basic Use of Axios
  • Ts package Axios
    • Why package axios
      • Primary package
      • Secondary package
    • How to package
      • First package
      • Second package
      • Use

What is Axios

Axios is a Promise-based network request library (similar to jQuery’s Ajax for HTTP requests) that works in node.js and browsers.

Comparison

1. AJAX

AJAX is a technology that can update some Web pages without reloading the entire Web page. It is a technical term.

2. $.ajax Method for jQuery

Ajax’s simplification, jQuery is a well-packaged JavaScript library, so jQuery’s $.ajax approach is simpler than native Ajax’s Disadvantages: Relying on the jQuery, the configuration is cumbersome, and the selection is not lightweight. Suggestion: The project already uses the jQuery, and there is no special requirement for the HTTP request.

3. Axios

Promise-based network request library for sending HTTP requests in browsers and Node.js. Axios is a package implemented by ajax through promise technology. In itself, axios is ajax .

4. XMLHttpRequest

XMLHttpRequest is a browser built-in JavaScript object that allows developers to request data from the server and receive server responses without refreshing the page. Is the base of Ajax Disadvantages: Both configuration and invocation are cumbersome Choice Recommendations: Developing an application that requires compatibility with old browsers or requires more granular control of HTTP requests

5. Fetch

After Fetch API ES6, a JavaScript library based on Promise appeared, which is a modern network request APIs,

 // ————————axios getThe first way to write method————————

// getmethod——————1.without parameters
axios.get('http://jsonplaceholder.typicode.com/posts')
  .then(function (response) {
    // Handle success situations
    console.log(response.data);
  })
  .catch(function (error) {
    // Handle error conditions
    console.log(error);
  });

// getmethod——————2.With parameters

// method one:Parameters are written inurlmiddle
axios.get('http://jsonplaceholder.typicode.com/posts/2')
  .then(function (response) {
    // Handle success situations
    console.log(response.data);
  })
  .catch(function (error) {
    // Handle error conditions
    console.log(error);
  });

// Method 2:Parameters are written inparamsmiddle
axios.get('http://jsonplaceholder.typicode.com/posts',{
  params:{
    id:2
  }
})
  .then(function (response) {
    // Handle success situations
    console.log(response.data);
  })
  .catch(function (error) {
    // Handle error conditions
    console.log(error);
  });

// ————————axios getThe second way of writing method————————

  // getmethod——————1.without parameters
    axios({
      method:'get',
      url:'http://jsonplaceholder.typicode.com/posts', 
      }).then(res =>{
        console.log(res.data) 
      })  

  // getmethod——————1.With parameters
      axios({
        method:'get',
        url:'http://jsonplaceholder.typicode.com/posts', 
        params:{
            id:2
          } 
        }).then(res =>{
          console.log(res.data) 
        })   

// ————————axios postThe first way to write method————————
      // postThere are two commonly used data request formats:
      // application/json
      // form-data form submission(upload picture、File Upload)



      // application/json
      axios.post("/user", "id=123&name=zs")
        .then(res=>{
            console.log(res)
          });

     axios.post("/user", {
        id:123,
        name:'zs'
        })
        .then(res=>{
        console.log(res.data)
        });

        let data = {id:123,name:"zs"}
        axios({
          method:'post',
          url:'/user',
          // andgetRequest to useparamsthe difference is,postRequest to usedataAttributes
          data:data,
          }).then(res=>{
            console.log(res)
          })

      // form-data form submission(upload picture、File Upload)

        let data = {id:123,name:"zs"}
        let formData = new FormData();
        for (let key in data) {
          formData.append(key, data[key]);
        }
        console.log(formData);
        axios.post("/user", formData)
        .then((res) => {
          console.log(res.data);
        });

// ————————axios putmethod————————

      axios.put("/user", {id:123,name:"zs"})
      .then(res=>{
      console.log(res)
      });

      axios.put("/user", data)
      .then(res=>{
      console.log(res)
      });

      axios({
          method:'put',
          url:'/user',
          // andgetRequest to useparamsthe difference is,postRequest to usedataAttributes
          data:data,})
          .then(res=>{
            console.log(res)
          })


// ————————axios patchmethod————————

      axios.patch("/user", {id:123,name:"zs"})
      .then(res=>{
      console.log(res)
      });

      axios.patch("/user", data)
      .then(res=>{
      console.log(res)
      });

      axios({
          method:'patch',
          url:'/user',
          // andgetRequest to useparamsthe difference is,postRequest to usedataAttributes
          data:data,})
          .then(res=>{
            console.log(res)
          }) 

6. Summary

  1. Ajax is a general term for technology, a term for js asynchronous technology, and XMLHttpRequest is a way to implement Ajax.
  2. JQuery’s $.ajax method is a method that encapsulates Ajax
  3. Axios is a library that is a third-party library for network requests.
  4. Fetch is a api and is a new standard api for network request added by es6.
  5. XHR is a JavaScript object that encapsulates Ajax

Basic Use of Axios

Get: Generally used to obtain data post: Generally used to submit data (form submission and file uploading) patch: Update data (only the modified data is pushed to the back end (server)) (applicable to updates with large data volume) put: Update data (all data is pushed to the server) (applicable to updates with small data volume) delete: Delete data

 // ————————axios getThe first way to write method————————

// getmethod——————1.without parameters
axios.get('http://jsonplaceholder.typicode.com/posts')
  .then(function (response) {
    // Handle success situations
    console.log(response.data);
  })
  .catch(function (error) {
    // Handle error conditions
    console.log(error);
  });

// getmethod——————2.With parameters

// method one:Parameters are written inurlmiddle
axios.get('http://jsonplaceholder.typicode.com/posts/2')
  .then(function (response) {
    // Handle success situations
    console.log(response.data);
  })
  .catch(function (error) {
    // Handle error conditions
    console.log(error);
  });

// Method 2:Parameters are written inparamsmiddle
axios.get('http://jsonplaceholder.typicode.com/posts',{
  params:{
    id:2
  }
})
  .then(function (response) {
    // Handle success situations
    console.log(response.data);
  })
  .catch(function (error) {
    // Handle error conditions
    console.log(error);
  });

// ————————axios getThe second way of writing method————————

  // getmethod——————1.without parameters
    axios({
      method:'get',
      url:'http://jsonplaceholder.typicode.com/posts', 
      }).then(res =>{
        console.log(res.data) 
      })  

  // getmethod——————1.With parameters
      axios({
        method:'get',
        url:'http://jsonplaceholder.typicode.com/posts', 
        params:{
            id:2
          } 
        }).then(res =>{
          console.log(res.data) 
        })   

// ————————axios postThe first way to write method————————
      // postThere are two commonly used data request formats:
      // application/json
      // form-data form submission(upload picture、File Upload)



      // application/json
      axios.post("/user", "id=123&name=zs")
        .then(res=>{
            console.log(res)
          });

     axios.post("/user", {
        id:123,
        name:'zs'
        })
        .then(res=>{
        console.log(res.data)
        });

        let data = {id:123,name:"zs"}
        axios({
          method:'post',
          url:'/user',
          // andgetRequest to useparamsthe difference is,postRequest to usedataAttributes
          data:data,
          }).then(res=>{
            console.log(res)
          })

      // form-data form submission(upload picture、File Upload)

        let data = {id:123,name:"zs"}
        let formData = new FormData();
        for (let key in data) {
          formData.append(key, data[key]);
        }
        console.log(formData);
        axios.post("/user", formData)
        .then((res) => {
          console.log(res.data);
        });

// ————————axios putmethod————————

      axios.put("/user", {id:123,name:"zs"})
      .then(res=>{
      console.log(res)
      });

      axios.put("/user", data)
      .then(res=>{
      console.log(res)
      });

      axios({
          method:'put',
          url:'/user',
          // andgetRequest to useparamsthe difference is,postRequest to usedataAttributes
          data:data,})
          .then(res=>{
            console.log(res)
          })


// ————————axios patchmethod————————

      axios.patch("/user", {id:123,name:"zs"})
      .then(res=>{
      console.log(res)
      });

      axios.patch("/user", data)
      .then(res=>{
      console.log(res)
      });

      axios({
          method:'patch',
          url:'/user',
          // andgetRequest to useparamsthe difference is,postRequest to usedataAttributes
          data:data,})
          .then(res=>{
            console.log(res)
          }) 

Ts package Axios

Why package axios

Looking at the code below, we find that we only need to change the method, the request path, and the data returned by the request. However, we need to write a lot of things each time. Can we just write what we need? Can we omit other things? At this point we can package the axios

 axios({
        method:'get',
        url:'http://jsonplaceholder.typicode.com/posts', 
        }).then(res =>{
          console.log(res.data) 
        })   

 axios({
        method:'get',
        url:'http://jsonplaceholder.typicode.com/posts', 
        params:{
            id:2
          } 
        }).then(res =>{
          console.log(res.data) 
        }) 

Primary package

http({
        url: '/api/v1/register',
        method: 'POST',
        data,
    }); 

After one encapsulation, we only need to pass in the get or post method, the request path, and the data returned by the request, but is the code too redundant if the request is required for multiple pages?

Secondary package

import {getInfor} from './axios/request'
const response = await getInfor(); 
//./axios/request.js
export const postRegister = (data) => {
    return http({
        url: '/api/v1/register',
        method: 'POST',
        data,
    });
}; 

After the secondary encapsulation, we only need to introduce the getInfor method to implement the network request.

How to package

First package

//http.js
import axios from "axios";

    // 1. createaxiosExample
    const instance = axios.create({
      baseURL: "http://jsonplaceholder.typicode.com",//Requested domain name  url = baseURL + requestUrl
      timeout: 5000,// Request timeout
      // headers: { //Set request header
      //   "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
      // },
    });

    // ​2. axiosUse of interceptors
    /** Reasons why requests need to be intercepted
     *   1.configcontains some information that does not meet the server's requirements
     *   2.When sending a network request, you need to display some loading icons to the user.
     *   3.The website requires login to request resources,That is, needtokento request resources
     */

    // 2.1 Add request interceptor
    // Add public request header、Handle request parameters, etc.
    instance.interceptors.request.use(
      (config) => {
        // What to do before sending a request

        const token = localStorage.getItem('token')
        if (token) {
            config.headers.Authorization = `Bearer {token}`;
        }


        return config; //In the interceptor, you must remember to process the intercepted results and return them,Otherwise, data acquisition cannot be performed
      },
      (err) => {
        // What to do about request errors

        return Promise.reject(err); // Logical processing when request error
      }
    );


    // 2.2 Add response interceptor
    // Modify response information,Such as data conversion、Error handling etc.
    instance.interceptors.response.use(
      (res) => {
        // Process the response data after the request is successful
        // console.log(res.data);
        if (res.status === 200) {
          return res.data;
        }      },
      (err) => {
        // What to do about response errors
        if(err.response.status){
            switch (err.response.status) {
                case 400:
                // Handle error messages,For example, throw an error message,Or jump to the page and other processing methods。
                  err.message = "Bad request";
                  break;
                case 401:
                  err.message = "unauthorized,please login again";
                  break;
                case 403:
                  err.message = "access denied";
                  break;
                case 404:
                  err.message = "Request error,The resource was not found!!!!";
                  alert(err.message)
                  break;
                case 405:
                  err.message = "Request method not allowed";
                  break;
                case 408:
                  err.message = "Request timed out";
                  break;
                case 500:
                  err.message = "Server side error";
                  break;
                case 501:
                  err.message = "Network is not implemented";
                  break;
                case 502:
                  err.message = "Network Error";
                  break;
                case 503:
                  err.message = "service is not available";
                  break;
                case 504:
                  err.message = "network timeout";
                  break;
                case 505:
                  err.message = "httpThe version does not support the request";
                  break;
                default:
                  err.message = `connection error{err.response.status}`;
            }
        }


        return Promise.reject(err); // Logical processing when responding to errors
      }
    );

export default instance; 

Second package

import http from './http'

export const getInfor = ()=>{
    return http({
            method:'get',
            url:'/posts', 
      })
}     

export const getInforDetail = (params)=>{
      return http({
              method:'get',
              url:'/posts', 
              params
        })
  } 

Use

 <script lang="ts" name="" setup>
    import axios from 'axios';
    import {getInfor,getInforDetail,postInfor } from './axios/request'

    async function get() {  
        const response = await getInfor(); // waitPromiseparse 
        console.log(response);
        const response1 = await getInforDetail( {id:2}); // waitPromiseparse 
        console.log(response1);
    }  
   get(); 

From

 // ————————axios getThe first way to write method————————

// getmethod——————1.without parameters
axios.get('http://jsonplaceholder.typicode.com/posts')
  .then(function (response) {
    // Handle success situations
    console.log(response.data);
  })
  .catch(function (error) {
    // Handle error conditions
    console.log(error);
  });

// getmethod——————2.With parameters

// method one:Parameters are written inurlmiddle
axios.get('http://jsonplaceholder.typicode.com/posts/2')
  .then(function (response) {
    // Handle success situations
    console.log(response.data);
  })
  .catch(function (error) {
    // Handle error conditions
    console.log(error);
  });

// Method 2:Parameters are written inparamsmiddle
axios.get('http://jsonplaceholder.typicode.com/posts',{
  params:{
    id:2
  }
})
  .then(function (response) {
    // Handle success situations
    console.log(response.data);
  })
  .catch(function (error) {
    // Handle error conditions
    console.log(error);
  });

// ————————axios getThe second way of writing method————————

  // getmethod——————1.without parameters
    axios({
      method:'get',
      url:'http://jsonplaceholder.typicode.com/posts', 
      }).then(res =>{
        console.log(res.data) 
      })  

  // getmethod——————1.With parameters
      axios({
        method:'get',
        url:'http://jsonplaceholder.typicode.com/posts', 
        params:{
            id:2
          } 
        }).then(res =>{
          console.log(res.data) 
        })   

// ————————axios postThe first way to write method————————
      // postThere are two commonly used data request formats:
      // application/json
      // form-data form submission(upload picture、File Upload)



      // application/json
      axios.post("/user", "id=123&name=zs")
        .then(res=>{
            console.log(res)
          });

     axios.post("/user", {
        id:123,
        name:'zs'
        })
        .then(res=>{
        console.log(res.data)
        });

        let data = {id:123,name:"zs"}
        axios({
          method:'post',
          url:'/user',
          // andgetRequest to useparamsthe difference is,postRequest to usedataAttributes
          data:data,
          }).then(res=>{
            console.log(res)
          })

      // form-data form submission(upload picture、File Upload)

        let data = {id:123,name:"zs"}
        let formData = new FormData();
        for (let key in data) {
          formData.append(key, data[key]);
        }
        console.log(formData);
        axios.post("/user", formData)
        .then((res) => {
          console.log(res.data);
        });

// ————————axios putmethod————————

      axios.put("/user", {id:123,name:"zs"})
      .then(res=>{
      console.log(res)
      });

      axios.put("/user", data)
      .then(res=>{
      console.log(res)
      });

      axios({
          method:'put',
          url:'/user',
          // andgetRequest to useparamsthe difference is,postRequest to usedataAttributes
          data:data,})
          .then(res=>{
            console.log(res)
          })


// ————————axios patchmethod————————

      axios.patch("/user", {id:123,name:"zs"})
      .then(res=>{
      console.log(res)
      });

      axios.patch("/user", data)
      .then(res=>{
      console.log(res)
      });

      axios({
          method:'patch',
          url:'/user',
          // andgetRequest to useparamsthe difference is,postRequest to usedataAttributes
          data:data,})
          .then(res=>{
            console.log(res)
          })