接口调用fetch
fetch基本用法
fetch('/abc').then(data=>{
//这里返回的其实是一个Promise对象,text()方法属于fetchAPI的一部分
return data.text();
}).then(ret=>{
//注意这里得到的才是最终的数据
console.log(ret);
});
fetch请求参数
-
常用配置选项
- method(String):HTTP请求方法,默认为GET(GETPOSTPUTDELETE)
- body(String):HTTP的请求参数
- headers(Object):HTTP的请求头,默认为{}
fetch('/abc',{ method: 'get' }).then(data=>{ return data.text() }).then(ret=>{ console.log(ret); });
-
POST请求方式的参数传递
fetch('/login',{ method: 'post', body: 'uname=admin&pwd=123', headers:{ 'Content-Type':'application/x-www-form-urlencoded' } }).then(data=>{ return data.text(); }).then(ret=>{ console.log(ret); }); //--------------------json------------------- fetch('/login',{ method: 'post', body: JSON.stringify({ uname:'admin', pwd:123 }), headers:{ 'Content-Type':'application/json' } }).then(data=>{ return data.text(); }).then(ret=>{ console.log(ret); });
-
fetch响应结果
响应格式
- text(): 将返回体处理成字符型
- json():返回结果和JSON.parse(responseText)一样
fetch('/list').then(data=>{ return data.json(); }).then(ret=>{ console.log(ret); });