安装vue axios
npm install --save axios vue-axios
在main.js中引入
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
安装qs库
npm install qs
- 如果不使用qs库转换,那后端无法接受data中的数据
- 原因:默认情况下发送axios时请求头中的内容类型为:
Content-Type:application/json;charset=UTF-8
Content-Type:application/x-www-form-urlencoded
- 因此,使用axios的qs内置库中的方法进行内容类型的转换。
发送ajax请求
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);
});
跨域问题
- 前后端分离项目发送请求可能会出现跨域问题(也有可能不出现)
- 解决方法我收集了2种项目的方案
- springmvc项目
<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>