Vue Learning 02--How Vue uses axios to request the background asynchronously

Axios is a promise-based HTTP library that can be used in browsers and node.js.


feature

  • Create XMLHttpRequests from the browser 
  • Create http request from node.js 
  • Promise  API support 
  • Intercept requests and responses
  • Convert request data and response data
  • cancel the request
  • Automatically convert JSON data
  • Client support for  XSRF defense

Install

This project is opened and run using IDEA software. When installing axios, directly in Terminal, adding -D means adding the dependency to the DevDependencies of the package.json file

$ npm install axios -D


Quote Axios directly


// GET request
axios.get('/user?ID=1')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// POST request
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });


Use Axios globally

First, create a new HttpUtil.js file in the file of the public method you built. The following is the content of HttpUtil.js:

var axios = require ( 'axios' )

// Configure project root such as path
 var root = 'http://localhost:8090/manage'
 // axios request
 function httpApi (method, url, params) {
   return new Promise((resolve, reject) => {
     axios ({
       method : method,
       url : url,
       data : method === 'POST' || method === 'PUT' ? params : null ,
       params : method === 'GET' || method === 'DELETE' ? params : null ,
       baseURL : root ,
      
withCredentials: false
    }).then(
      (response) => {
        resolve(response)
      }
    ).catch(
      (error) => {
        reject(error)
      }
    )
  })
}

// Return the calling interface in the vue template
 export default {
   get : function (url, params) {
     return httpApi ( 'GET' , url, params)
  },
  post: function (url, params) {
    return httpApi('POST', url, params)
  },
  put: function (url, params) {
    return httpApi('PUT', url, params)
  },
  delete: function (url, params) {
    return httpApi('DELETE', url, params)
  }
}
 
 

Make global settings in main.js


In this way, the global setting of Axios is completed, and the asynchronous request method of Axios can be directly referenced in other components


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325166607&siteId=291194637