axios in vue

Keywords: Javascript axios npm JSON Vue

axios

promise based on http client for browser and nodejs

characteristic

  • Browser side initiates XMLHttpRequests request

  • http request from node

  • Support Promise API

  • Listen for requests and returns

  • Conversion request and return

  • Cancellation request

  • Automatically convert json data

  • Client support mitigation

install

Using npm:

npm install axios --save

In order to solve the problem that the application/json request data is used by default for post, so the request parameters cannot be passed to the background. Therefore, a plug-in QS needs to be installed, which converts the application/json to application/x-www-from-urlencoded

npm install qs --save

One command all solved

npm install --save axios vue-axios qs

Use

Modify prototype chain

First, introduce axios in main.js

import Axiso from 'axiso'

At this time, if you are in other components, you cannot use the axios command. But if you rewrite axios as the prototype property of Vue, you can solve this problem

Vue.prototype.$axios= Axios

Once configured, it can be used globally

post request conversion

import QS from 'qs'

if(config.method=='post'){
config.data=QS.stringify(config.data);//Prevent post request parameters from being sent to the background
}

Instance use:

axios({
    method: 'post',
    url:'http://easy-mock.com/mock/596077559adc231f357bcdfb/axios/test-post-axios'
  })
  .then((response)=>{
      console.log(response.data)
  })
  .catch((error)=>{
      console.log(error)
  })
  
  axios.post('http://easy-mock.com/mock/596077559adc231f357bcdfb/axios/test-post-axios',{
      miaov:"Classroom"  //Data sent
    })
      .then((response)=>{
        console.log(response.data)
      })
      .catch((error)=>{
        console.log(error)
      })

Send with parameters

//Send data by get
axios.get('https://easy-mock.com/mock/5a883cccbf160328124e8204/example/mock', {
    params: {
        pomelo: 'tt',
        test: 'test'
    }
}).then((response) => {
    console.log(response)
}).catch((error) => {
    console.log(error)
})
//Send data by post
axios.post('https://easy-mock.com/mock/5a883cccbf160328124e8204/example/mock', {
    pomelo: 'tt',
    test: 'test'
}).then((response) => {
    console.log(response)
}).catch((error) => {
    console.log(error)
})

Posted by mjahkoh on Fri, 07 Feb 2020 10:38:51 -0800