Js uses native Ajax

A get request

var xhr = new XMLHttpRequest()
xhr.open('get', url, true)
xhr.send()
xhr.onreadystatechange = () => {
    if(xhr.readState == 4){
        if(xhr.readState == 200){
            console.log(xhr.responseText)
        }
    }
}
Copy the code

A post request

var xhr = new XMLHttpRequest()
xhr.open('post', url, true)
xhr.setRequestHeader('content-type'.'xxx')
xhr.send(data)
xhr.onreadstatechange = () => {
    if(readState == 4){
        if(readState == 200){
            console.log(xhr.responseText)
        }
    }
}
Copy the code

Vue uses axios to request

Since Vue itself does not support sending Ajax requests, plug-ins such as Axios are needed to implement using vuE-CLI scaffoldingCopy the code
  1. The installation
    npm install axios -S
    Copy the code
  2. use
  • Unwrapped the request

    • Introduce Axios in main.js
    import axios from 'axios'
    Copy the code
    • Mount the AXIos method on the Vue prototype for global use
    Vue.prototype.axios = axios
    Copy the code
    • Components use
    Get method this.axios.get(url).then(() => {}).catch((err) => {})'content-type':'application/json'
        }
    }).then(() => {}).catch((err) => {})
    Copy the code
  • Encapsulating request requests

    • request.js
    // import axios from'axios'// Create an instance of axios const service = axios.create({baseUrl:'http://',
        withCredentials: true, / / cross-domain sent cookie timeout: 5000}) / / request interceptor serive. Interceptors. Request. Use (config = > {if(store.getters.token){
                config.headers['X-Token'] = getToken()
                //config.headers['Authorization'] = 'Bearer ' + getToken()
            }
            return config
        },
        error => {
            console.log(error)
            returnPromise. Reject (error)}) / / response interceptor serive. Response. Interceptors. Use (response = > {const res = response. The dataif(res == 200){
                return res
            }
        },
        error => {
            console.log(error)
            return Promise.reject(error)
        }
    )
    Copy the code
    • Encapsulate the API and introduce request in the API folder
    import request from '@/untils/request'
    
    export function getData(query){
        return request(
            url: '/data/.. ',
            methods:' get',
            params: query
        })
    }
    
    export function updateData(data){
        return request({
            url:' ',
            methods:'post',
            data
        })
    }
    Copy the code
    • Used in components
    1, introduce API import getData from'@/api/'
    import updateData from '@/api/.. '
    methods:{
        getData(){
            getData('123').then(() => {
            })
        },
        updateData(){
            updateData('ad').then(() => {
            })
        }
    }
    Copy the code