(1) vue-resource请求
从vue的2.0开始,作者说:vue-resource不再维护了
(2) fetch请求(规范)
why: XMLHttpRequest 是一个设计粗糙的 API,配置和调用方式非常混乱, 而且基于事件的异步模型写起来不友好。
查看兼容性
兼容性不好,可以借助polyfill实现兼容
1 //get
2 fetch("**?a=1&b=2").then(res=>res.json()).then(res=>{console.log(res)})
3 fetch("**").then(res=>res.text()).then(res=>{console.log(res)})
4 //post
5 fetch("**",{
6 method:'post', //必须指明post请求方式,默认是get
7 headers: {
8 "Content‐Type": "application/x‐www‐form‐urlencoded"
9 },
10 body: "name=zhangsan&age=100"
11 }).then(res=>res.json()).then(res=>{console.log(res)});
12 fetch("/users",{
13 method:'post',
14 // credentials: 'include',
15 headers: {
16 "Content‐Type": "application/json"
17 },
18 body: JSON.stringify({
19 name:"zhangsan",
20 age:100
21 })
22 }).then(res=>res.json()).then(res=>{console.log(res)});
Fetch 请求默认是不带 cookie 的,需要设置 fetch(url, {credentials: ‘include’})*
(3) axios请求
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
特性:
从浏览器中创建 XMLHttpRequests
从 node.js 创建 http 请求
支持 Promise API
拦截请求和响应
转换请求数据和响应数据
取消请求
自动转换 JSON 数据
客户端支持防御 XSRF
安装:
1、使用 npm:
$ npm install axios
2、使用 bower:
$ bower install axios
案例:
// get
axios.get("json/test.json?name=zhangsan&age=10").then(res=>{
// res.data 才是真正的后端数据
console.log(res.data.data.films)
this.datalist = res.data.data.films
})
//post -1- x-www-form-urlencode
axios.post("json/test.json","name=zhangsan&age=10").then(res=>{
console.log(res.data)
})
//post -2- application/json
axios.post("json/test.json",{
name:"zhangsan",
age:100
}).then(res=>{
console.log(res.data)
})