Vue--前端交互 fetchAPI

1. fetch基本使用

  • fetch 就是 ajax + Promise. 使用的方式和 jquery 提供的 $.ajax() 差不多
  • fetch默认是get请求
//基本用法
		fetch('http://localhost:3000/data')
            .then(function (data) {
         	//text() 方法属于fetchAPI的一部分,他返回一个Promise实例对象,用于获取后台返回的数据
                return data.text();
            }).then(function (data) {
            //注意这里才是最终数据
                console.log(data);
            })

2. fetch请求参数

1.常用配置选项
  • method(String) :HTTP请求方式,默认为get
  • body(String) :HTTP的请求参数
  • headers(Object):HTTP的请求头,默认为{}
2.get请求参数的参数传递
		fetch('http://localhost:3000/books/456', {
                method: 'get'
            })
            .then(function (data) {
                return data.text();
            }).then(function (data) {
                console.log(data);
            })
3.delete方式传参
		fetch('http://localhost:3000/books/789', {
                method: 'delete'
            })
            .then(function (data) {
                return data.text();
            }).then(function (data) {
                console.log(data);
            })
4.post请求方式传参

post和put请求:

  • 需要在body 中传递参数
  • 需要指定headers
		fetch('http://localhost:3000/books', {
                method: 'post',
            body: 'uname=lisi&pwd=123',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            }
            })
            .then(function (data) {
                return data.text();
            }).then(function (data) {
                console.log(data);
            })
5.put请求方式传参
	fetch('http://localhost:3000/books/123', {
            method: 'put',
            body: 'uname=lisi&pwd=123',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            }
        }).then(function (data) {
            return data.text();
        }).then(function (data) {
            console.log(data)
        })

3. fetch响应结果

响应数据格式

  • text():将返回处理成字符串类型
  • json():返回结果和JSON.parse(responseText)一样
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值