数据请求的几种方式

(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)
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值