Vue Axios request essay

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

###Axios features

1. Create XMLHttpRequests from the browser

2. from node.js establish http request
3. support Promise API
4. Intercept requests and responses
5. Convert request data and response data
6. Cancel request
7. Automatic conversion JSON data
8. Client support defense XSRF

install

npm install axios -S

  1. Global reference
import axios from 'axios'   
Vue.prototype.$axios = axios
//Used in the subcomponent mounted lifecycle function 
this.$axios.get("http://xx")
.then(res=>{console.log(res)})
.catch(error=>{console.log(error)})
  1. Local reference
import $axios from 'axios'
//Used in the component mounted lifecycle function 
$axios.get("http://xx").then(res=>{console.log(res)})
//Second writing format:
$axios.get("http://iwenwiki.com/api/music/list.php",{
        params:{
                   type:1,
                   count:10,
                offset:0
            }
    }).then(res=>{
    console.log(res)
    })
  1. You can also create a request by passing the relevant configuration to axios
$axios({
     method:'post',
      url:"http://iwenwiki.com/api/blueberrypai/login.php",
      data:qs.stringify({
            user_id:"iwen@qq.com",
              password:"iwen123",
              verification_code:"crfvw"
      })
}).then(...)

Request configuration options
These are the configuration options available when creating a request. Only url is required. If no method is specified, the request will use the get method by default.

{
    url       //URL is the server URL used for the request
    method      //Method ` is the method used when creating the request
    baseURL     //Will be automatically added before 'url', unless the url is an absolute url
    transformRequest: [function (data, headers) { //Allows you to modify the request data before sending it to the server
                return data;    // Arbitrary conversion of data
      }],
    transformResponse: [function (data) { //It is allowed to modify the response data before passing it to then/catch
               return data;// Arbitrary conversion of data
      }],
    headers    //Is the custom request header to be sent
    params: {     //The URL to be sent with the request is
                ID: 12345
      },
     data: {
                firstName: 'Fred'
      },    
    timeout: 1000,
    responseType: 'json',
      //View document http://www.axios-js.com/zh-cn/docs/#axios -There are many more APIs
           }

Response structure
The response to the request contains the following information:
data{ } , status , statusText , headers , config , request

  1. For convenience, all request methods are aliased

When using alias methods, the attributes url, method and data need not be specified in the configuration.

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]])

Request method: Get / Post

  1. Get request: $Axios get(" http://xx ").then()
  2. Post request: you need to use querystring to convert the object form of the parameter into a string, because the parameter accepted by axios is a string type
 import qs from 'query-string'
  $axios.post("http://xx",qs.stringify({
                user_id:"iwen@qq.com",
            password:"iwen123",
              verification_code:"crfvw"
          })).then()

Execute multiple concurrent requests

Helper functions used to handle concurrent requests:
axios.all(iterable) and Axios spread(callback)

function AA(){
         return     $axios.get("http://xx ") / / do not add. then()
    }
function BB(){
         return     $axios.get2/post("http://xxx");
    }
    
$axios.all([AA(),BB()])
.then($axios.spread((AA,BB)=>{console.log(AA,BB)}))

Custom create instance

const instance = axios.create({
            baseURL : "http://xxx",
            timeout : 1000,
            headers : {'X-Custom-Header': 'foobar'}
    })

Configure default value [key]

Global axios default
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

Interceptor

Intercept requests or responses before they are processed by then or catch.

  1. Add request interceptor
axios.interceptors.request.use(function (config) {
        // What to do before sending the request
             // to configure
            if(config.method === 'post'){
                    config.data = qs.stringify(config.data);
            }
                return config;
           }, function (error) {
                   // What to do about request errors
                 return Promise.reject(error);
          });
  1. Add response interceptor
axios.interceptors.response.use(function (response) {
        // Do something about the response data
         return response.status === 200 ? Promise.resolve(response) : Promise.reject(response),
      }, function (error) {
         // Do something about response errors
         return Promise.reject(error);
      });

To remove the interceptor later, you can:

const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

Cross domain processing

  1. Development environment cross domain solution: Proxy proxy (valid only in development environment).

    Usage scenario:
       1.Background developers don't have time to deal with cross domain issues  
       2.Simulate the data server yourself, for example mock Generate cross domain)
       

    Step 1: create the configuration file vue.exe under the project root directory config. JS, and then configure the file. Each time you modify the file, you must restart the project

module.exports = {
    devServer:{
        proxy:{
            "api":{
                target:"http://iwenwiki.com ", / / proxy request address
                pathRewrite:{  //Rewrite path
                    "^/api":"/api/FingerUnion"; //address
                    },
                changeOrigin:true  //Allow cross domain
            }
        }
    }
}

Step 2: select base. Under the api file JS (storage path) add configuration proxyurl: "/ api"

const base = {
                baseURL:"http://iwenwiki.com",
                proxyURL:"/api",
                     banner:"/api/blueberrypai/getIndexBanner.php",
                list:"/list.php",
        }
export default base;

Step 3: index. In the api file Encapsulate request data in JS (encapsulate request)

import base from './base'
import axios from '../utils/request'

const api = {
        getBanner(){
            return axios.get(base.baseURL+base.banner)
        },
        getList(params){
            return axios.get(base.proxyURL+base.list,{
                    params:params
                })
        }
}

export default api;

Step 4: import the api file into the global main JS or any component, import api from '/ api ', if it is introduced into the global, you need to mount the api on the Vue prototype (Vue.prototype.$api = api;), Then call the encapsulated network request function in the api

this.$api.getList({    //This example introduces the api to the global
          page:1
        }).then(res=>{
          console.log(res.data);
})
  1. Cross domain solution of development environment: cross domain solution of CORS background

Cross domain solution for production environment: CORS background solution

Tags: Front-end Vue.js

Posted by otuatail on Sun, 15 May 2022 20:16:08 +0300