前端向后端发送请求的⽅式总结
⼀、uniapp
1、quest({ })
url: '/api/index_category/data',
method: 'GET',
success: res => {
console.log(res);
},
fail: () => {
console.log('请求失败');
},
complete: () => {
console.log('请求完成');
}
})
⼆、vue
vue不⽀持直接发送AJAX请求,需要使⽤vue-resource、axios等插件实现。
1、Axios⽅式(推荐)
1. 安装axios并引⼊:
1. npm install axios -S (直接下载axios组件,下载完毕后axios.js就存放在node_modules\axios\dist中),⾸先在 main.js 中引⼊
axios:在此⽂件加⼊import axios from 'axios',如果在其它的组件中⽆法使⽤ axios 命令。可以将 axios 改写为 Vue 的原型属性:Vue.prototype.$http=axios,在 main.js 中添加了这两⾏代码之后,就能直接在组件的 methods 中使⽤ this.$http命令。
2. ⽹上直接下载axios.min.js⽂件,通过script src的⽅式进⾏⽂件的引⼊ 
2. 发送请求: 
1. get请求使⽤格式:
1. axios([options]) (这种格式直接将所有数据写在options⾥,options其实是个字典)
2. (url[,options]); 
3.
<script>
new Vue({
el:'#itany',
data:{
user:{
name:'alice',
age:19
},
},
methods:{
send(){
axios({//格式a
method:'get',
url:'www.baidu?name=tom&age=23'
}).then(function(resp){
console.log(resp.data);
}).catch(resp => {
console.log('请求失败:'+resp.status+','+resp.statusText);
});
},
sendGet(){//格式b
<('server.php',{
params:{
name:'alice',
age:19
}
})
.then(resp => {
console.log(resp.data);
}).catch(err => {            //
console.log('请求失败:'+err.status+','+err.statusText);
});
},
}
});
</script>
代码部分
2. post请求格式:
1. axios.post(url,data,[options]); 
2.
new Vue({
el:'#itany',
data:{
user:{发送ajax请求的步骤
name:'alice',
age:19
},
},
methods:{
sendPost(){
// axios.post('server.php',{
//        name:'alice',
//        age:19
// }) //该⽅式发送数据是⼀个Request Payload的数据格式,⼀般的数据格式是Form Data格式,所有发送不出去数据
// axios.post('server.php','name=alice&age=20&') //⽅式1通过字符串的⽅式发送数据
axios.post('server.php',this.user,{  //⽅式2通过transformRequest⽅法发送数据,本质还是将数据拼接成字符串
transformRequest:[
function(data){
let params='';
for(let index in data){
params+=index+'='+data[index]+'&';
}
return params;
}
]
})
.then(resp => {
console.log(resp.data);
}).catch(err => {
console.log('请求失败:'+err.status+','+err.statusText);
});
},
}
});
代码部分
3. 发送跨域请求:
1. 须知:axios本⾝并不⽀持发送跨域的请求,没有提供相应的API,作者也暂没计划在axios添加⽀持发送跨域请求,所以只
能使⽤第三⽅库
2. 使⽤vue-resource发送跨域请求
3. 安装vue-resource并引⼊
   npm info vue-resource          #查看vue-resource 版本信息
  cnpm install vue-resource -S #等同于cnpm install vue-resource -save
4. 基本使⽤⽅法(使⽤this.$http发送请求)
    this.$(url, [options])
    this.$http.head(url, [options])
    this.$http.delete(url, [options])
    this.$http.jsonp(url, [options])
    this.$http.post(url, [body], [options])
   this.$http.put(url, [body], [options])
    this.$http.patch(url, [body], [options])
三、html
四、
原⽂地址2