Brief introduction of axios and the use of axios in vue (detailed)


If you want to learn something, it is the most important thing to have a deep understanding of it! ! !
Axios is a kind of encapsulation of ajax technology through promise, similar to jQuery's encapsulation of ajax, but we use vue to develop purely using ajax, but it is very unreasonable to introduce the entire JQuery (the personalized packaging scheme can not enjoy CDN Service) not recommended! ! !

Axios in brief

Axios is actually encapsulated ajax, which is essentially a encapsulation of native XHR, but it is an implementation version of Promise, which complies with the latest ES specifications.
Features of axios:
1. Create XMLHttpRequest from the browser
2. Support Promise API
3. Client support to prevent CSRF
4. Provide some concurrent request interfaces (important, convenient for a lot of operations)
5. Create from node.js HTTP request
6. Intercept request and response
7. Convert request and response data
8. Cancel request
9. Automatically convert JSON data
PS: Prevent CSRF: Simply put, let each request you have brought one from the cookie Key, according to the browser's same origin policy, the fake website cannot get the key in your cookie. In this way, the background can easily identify whether the request is a misleading input by the user on the fake website and adopt the correct strategy. More details can be found in this article


axios contrast with ajax

ajax code snippet:

$.ajax({
          url:'/frontMenu',
          type:'post',
          dataType:'json',//xml,html,script,jsonp,text类型
          data:{
                  menuName:this.menuName //按具体模块是否需要传参
              }, 
           success:function(response){
                          console.log(response)
                   }
           })

(ajax realizes the refresh of the partial data of the webpage)
axios code snippet (the axios API I use here):

 axios({
       url:'/frontMenu',
       method:'post',
       responseType:'json',//默认为json,
       data:{
                  menuName:this.menuName //按具体模块是否需要传参
            } })
               .then(funtion(response){
                   console.log(response)
                })
                  .catch(function(error){
                        console.log(error)
                   })

Add the responseType of axios:

Value (responseType) type of data
’ ’ DOMString
arraybuffer ArrayBuffer object (typed array)
blob Blob object (in addition to storing binary data, you can also set the MINE type of this data)
document Document object
json JavaScript object,parsed from a JSON string returned by the server
text DOMString

Pros and cons

ajax:
1. Ajax is mainly aimed at the MVC programming model. It is still lacking in today's front-end MVVC framework.
2. Based on native XHR development, the architecture of XMR itself is not clear, although there is already fetch (but axios has helped Our packaging is convenient enough, why do we have to spend a lot of effort to learn fetch and fetch is not so comfortable to use, it needs to be packaged.)

axios is the feature mentioned above, and it provides concurrent encapsulation and small size.

ps: As for fetch, the promise object in ES6 is used, and it is designed based on promise But it is not a encapsulation of ajax but native js, and does not use the XMLHttpBequest object.


Speaking of this, do you really want to know how to use axios in specific projects (๑→‿ฺ←๑)

Use of axios

Vue originally had an officially recommended ajax plugin vue-resource, but since Vue was updated to 2.0, the official no longer updates vue-resource. All current mainstream Vue projects choose axios to complete ajax requests

axios installation

Introduce axios in the corresponding file directory npm install --save axios vue-axios
or
use cdn :
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Method one (modify the prototype chain):
in the mian file

import axios from 'axios'

Vue.prototype.$axios = axios  //改变

When the component is used

      that.$axios
        .post("/frontMenu",{
                  menuName:this.menuName //按具体模块是否需要传参
        })
        .then(response => {
          console.log(response)
        })
        .catch(function(error) {
          console.log(error)
        });

Method two (combined with vue-axios)
vue-axios is written in the way of vue plugins. Then combined with vue-axios, you can use the vue.use method.
In the main file

import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios,axios);

Used in components

      this.axios.post('/frontMenu',{
                  menuName:this.menuName //按具体模块是否需要传参
      })
      .then((response)=>{
          console.log(response)
      }).catch((response)=>{
        console.log(error)
      });

Use of axios

Regular use
      this.axios.post('/frontMenu',{
                  menuName:this.menuName //按具体模块是否需要传参
      })
      .then((response)=>{
          console.log(response)
      }).catch((response)=>{
        console.log(error);
      })

ps: get method, just replace post with get, it will not be listed separately here

axios API

You can create a request by passing the relevant configuration to axios.

this.axios({
               method:'post',
               url:'/frontMenu',
               data:{
                  menuName:this.menuName //按具体模块是否需要传参
                 },
                 //修改请求头
                headers: {
                  "Content-Type": "application/x-www-form-urlencoded"
                        }
                })  
                  .catch(function(error) {
                         console.log(error)
                   });

Request header usage

1.Content-Type: application/json
这种是axios默认的请求数据类型,我们只需将参数序列化json字符串进行传递即可,
无需多余的配置
2.Content-Type: multipart/form-data
<input>元素的type属性必须为file
3.Content-Type:application/x-www-form-urlencoded
请求体中的数据会以普通表单形式(键值对)发送到后端
Concurrency of axios (axios.all, axios.spread)
   let axiosList=[
   axios.get('url1',{params:xxx,dateType:'JSON'}),
   axios.get('url2',{params:xxx,dateType:'TEXT'}),
]
axios.all(axiosList).then(axios.spread(function(res1,res2){
  console.log(res1,res2)//分别是两个请求的返回值
})
Request method alias

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
ps: When using the alias method, url, method, and data do not have to be specified in the configuration.

Common problems with value passing

1. It is a key-value pair when the foreground is passed, and the background is difficult to receive.
Solution: Use the qs library that comes with axios to serialize the parameters.
Introduce
import Qs from "qs";
the parameters first in the components that need to be used .

let data= Qs.stringify({
userName:this.userName,
passWord:this.passWord
})
this.axios({
               method:'post',
               url:'/frontMenu',
               data:data
                })       
                .then((response)=>{
          console.log(response)
                 }) 
                .catch(function(error) {
                         console.log(error)
                   });

console.log(data)
result: userName=hahahaha&&passWord=1234567
solves the problem perfectly (ฅ´ω`ฅ)
Add:

qs.parse() parses the URL into the form of an object

When we need to pass an array, we can handle it in the following way:
By default, they give a clear index, as in the following code:
qs.stringify({ a: ['b','c','d' ] });
//'a[0]=b&a[1]=c&a[2]=d'
can also be rewritten. The default method is false
qs.stringify({ a: ['b','c' ,'d'] }, {indices: false });
//'a=b&a=c&a=d'
Of course, you can also format the output through the arrayFormat option, as shown in the following code:
qs.stringify({ a: [ 'b','c'] }, {arrayFormat:'indices' })
//'a[0]=b&a[1]=c'
qs.stringify({ a: ['b','c']} , {arrayFormat:'brackets' })
//'a[]=b&a[]=c'
qs.stringify({ a: ['b','c'] }, {arrayFormat:'repeat' })
// 'a=b&a=c'

2. Upload pictures.
Solution: You need to change the request header and submit with the form

  uploadFile(file) {
      this.formDate.append("file", file.file);
    },
 submitUpload() {
 this.formDate = new FormData();
 let config = {
          headers: {
            "Content-Type": "multipart/form-data"
          }
        };
that.axios
          .post("/api/pictureUpload", this.formDate, config)
          .then(response => {
            console.log(response);          
          })
          .catch(response => {
            console.log(response);
          });
          }

ps: I use the image upload control in element-ui

to sum up

The choice of axios is in line with the current front-end development trend, and it is small and easy to use. As for more introduction about the axios configuration, leave it later (๑˘ ˘๑). This article explains the basic usage of axios and axios, and the usage of axios+vuex encapsulation will come out in the future! ! !

This article is slightly bloated. Thank you for watching ꒰๑´•.̫ • `๑꒱

Guess you like

Origin blog.csdn.net/weixin_44383354/article/details/102871613