2021-02-20-vue project uses axios

Install vue axios

npm install --save axios vue-axios

Introduced in main.js

  • Use the axios module in the project
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)

Install qs library

npm install qs
  • If you do not use the qs library conversion, the backend cannot accept the data in data
  • Reason: By default, the content type in the request header when sending axios is:
Content-Type:application/json;charset=UTF-8
  • What the actual server needs is:
Content-Type:application/x-www-form-urlencoded
  • Therefore, use the methods in the qs built-in library of axios for content type conversion.

Send ajax request

import Qs from "qs";
 this.axios({
          url: 'speedController/tokens',
          method: "post",
          transformRequest: [function (data) {
            return Qs.stringify(data)
          }],
          data:
            {
              username: 'admin',
              password: 'qwe!23'
            },

        }
      )
        .then(function (response) {
          console.log(response.data)
        })
        .catch(function (error) {
          console.log(error);
        });
        

Cross-domain issues

  • Cross-domain issues may occur when sending requests for front-end and back-end separation projects (or may not occur)
  • Solution I collected 2 kinds of project solutions
  • springmvc project
<mvc:cors>
<mvc:mapping path="/**"
allowed-origins="*"
allowed-methods="POST, GET, OPTIONS, DELETE, PUT,PATCH"
allowed-headers="Content-Type, Access-Control-Allow-Headers, Authorization, X-RequestedWith"
allow-credentials="true" />
</mvc:cors>

Guess you like

Origin blog.csdn.net/qq_41270550/article/details/113807507