方式一:使用URLSearchParams
第一步:在main.js里 设置配置,修改Content-Type
import Axios from 'axios';
Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Vue.prototype.$Axios = Axios;
jquery在执行post请求时,会设置Content-Type为application/x-www-form-urlencoded,所以服务器能够正确解析,而使用原生ajax、axios请求时,如果不显示的设置Content-Type,那么默认是text/plain,这时服务器就不知道怎么解析数据了,所以才只能通过获取原始数据流的方式来进行解析请求数据。
第二步:在组件vue里
export default {
methods: {
getData(id) {
let url = "http://localhost:8080/VueServer/news?op=detail";
let params = new URLSearchParams();
params.append("id",id.nid);
this.$Axios({
method: 'post',
url: url,
data: params //params会添加到url的请求字符串中,用于get请求。而data是添加到请求体(body)中的, 用于post请求。
}).then(res => {
this.msg = res.data;
console.info(res);
}).catch(error => {
console.info(error);
});
}
},
mounted() {
//获取动态传值
console.info(this.$route.params);
this.getData(this.$route.params);
}
}
方式二使用qs
第一步:安装qs
npm install qs
第二步:在 main.js里引入import Axios from 'axios';
import Qs from 'qs';
Vue.prototype.$Qs = Qs;
在vue组件里面请求方法
export default {
methods: {
getData(id) {
let url = "http://localhost:8080/VueServer/news?op=detail";
let params = this.$Qs.stringify({
id: id.nid
})
this.$Axios({
method: 'post',
url: url,
data: params
}).then(res => {
this.msg = res.data;
console.info(res);
console.info(this.msg);
}).catch(error => {
console.info(error);
});
}
},
mounted() {
//获取动态传值
console.info(this.$route.params);
this.getData(this.$route.params);
}
}