fetch 异步请求骚操作

概述

基于promise实现,xhr升级版

fetch(url).then(fn1)
			.then(fn2)
			......
			.catch(fn)

基本用法

fetch(url).then(data => {
	return data.text();//fetch API,返回promise实例对象
}).then(ret => {
	console.log(ret);//最终真实数据在这里!!
})

基本配置

1、method(String),http请求方式,默认GET
2、body(String),http请求参数
3、headers(Object),http请求头,默认0

//GET方式
fetch(url,{method:'get'}).then(data => {
	return data.text();
}).then(ret => {
	console.log(ret)
})

//DELETE方式
fetch(url,{method:'delete'}).then(data => {
	return data.text();
}).then(ret => {
	console.log(ret)
})

//POST方式
fetch(url,{
	method:'post',
	body:'name=abc&pwd=666',
	headers:{
		'Content-Type':'application/x-www-form-urlencoded' //表单
	}
}).then(data => {
	return data.text();
}).then(ret => {
	console.log(ret)
})
//JSON格式参数
fetch(url,{
	method:'post',
	body:JSON.stringify({
		name:'abc',
		pwd:'123'
	}),
	headers:{
		'Content-Type':'application/json' //json
	}
}).then(data => {
	return data.text();
}).then(ret => {
	console.log(ret)
})

//PUT
fetch(url,{
	method:'put',
	body:JSON.stringify({
		name:'abc',
		pwd:'123'
	}),
	headers:{
		'Content-Type':'application/json'
	}
}).then(data => {
	return data.text();
}).then(ret => {
	console.log(ret)
})

响应结果

响应数据格式
text() 将返回数据处理成字符串
json() 将返回结果处理成json,hjson,和JSON.parse()一样

fetch(url,{method:'get'}).then(data => {
	return data.json();
}).then(ret => {
	console.log(ret)
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值