Solutions to problems encountered with axios in vue 2.0

 

At the time of Vue1.0, there was an officially recommended ajax plugin  vue-resource , but since Vue was updated to 2.0, the official no longer updated vue-resource.

At present, mainstream Vue projects choose  axios  to complete ajax requests. The following is a brief introduction to the use of axios. For specific usage, please refer to the npm link : https://www.npmjs.com/package/axios .

feature

  • do XMLHttpRequest from browser
  • Make HTTP requests from node.js
  • Promise  API support
  • Intercept requests and responses
  • Transform request and response data
  • cancel the request
  • Automatic conversion to JSON data
  • Client support to prevent XSRF

1. Install axios

npm install axios -S
//Use Taobao source
cnpm install axios -S
// use bower
bower install axios -S
//or use cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

When installing other plug-ins, you can directly introduce them in main.js and use Vue.use() to register, but axios is not a vue plug-in, so Vue.use() cannot be used, so you can only use Vue.use() for each request that needs to be sent. Immediate introduction in components.

In order to solve this problem, after introducing axios, we modified the prototype chain to make it more convenient to use.

//main.js

import axios from 'axios'
Vue.prototype.$http = axios

After adding these two lines of code in main.js, you can use the $http command directly in the methods of the component

methods: {
  postData () {
    this.$http({
      method: 'post',
      url: '/user',
      data: {
        name: 'xiaoming',
        info: '12'
      }
   })
}

2. How to submit form data when axios sends a post request?

In the project development, the background interface has been developed (connected to iOS and Android), and vue+axios is used for h5 development, but the result submitted by post reports an error, as shown in the following figure:

Later, I learned that the background data reception needs to submit data in the form of forms, and the default submission of post in axios is json data, so how do we submit form data with axios? See the link below for more information):

1. Simple, direct and effective (directly splicing data into strings)

this.$http.post('/app/user/login.do',
    "username=15989346035&pwd=xxxxx&skey=skey&type=1")
    .then(function(res){
        console.log(res.data.data.token)
    })
    .catch(function(err){
        console.log(err)
    })

2, can also be achieved

var params = new URLSearchParams();
    params.append('username', '15989346035');
    params.append('pwd', 'xxxxx');
    params.append('skey', 'skey');
    params.append('type', 1);
this.$http.post('/app/user/login.do',
    "username=15989346035&pwd=e10adc3949ba59abbe5")
    .then(function(res){
        console.log(res.data.data.token)
     })
    .catch(function(err){ console.log(err) })

3. The Internet searched and found that many people used it (I don’t know why, my test was not successful, you can try it and maybe use it)

axios({
    url: '/app/user/login.do',
    method: 'post',
    data: {
        username:18943980005,
        pwd:"XXXXX",
        skey:"skey",
        type:1
    },
    transformRequest: [function (data) {
        let ret = ''
        for (let it in data) {
            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
        }
        return right
    }],
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
})

Reference link:

axios send request: https://www.cnblogs.com/zhouyangla/p/6753673.html

                         https://www.jianshu.com/p/df464b26ae58

Post submit form data in axios: https://segmentfault.com/q/1010000008462977

                                          http://blog.csdn.net/wopelo/article/details/78783442

Guess you like

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