js fetch
1.请求数据
使用fetch请求,默认get
<button onclick="btn1()">btn1</button> <script> function btn1() { fetch('https://www.fastmock.site/mock/bfa9f3e6ea929ffff80b1d475c04eb21/api/test') .then(res => { console.log(res); return res.json(); }).then(data => { console.log(data); }); }; </script>
await版
<button onclick="btn2()">btn1</button> <script> async function btn2() { let res = await fetch('https://www.fastmock.site/mock/bfa9f3e6ea929ffff80b1d475c04eb21/api/test'); console.log(res); let data =await res.json(); console.log(data); } </script>
2.响应头和状态码
function btn1() { fetch('https://www.fastmock.site1/mock/1bfa9f3e6ea929ffff80b1d475c04eb21/api/test') .then(res => { console.log(res); if (res.ok && status == 200) { return res.json(); } else { throw new Error("状态码不是200"); } }) .then(data => { console.log(data); }) //如果浏览器离线或者服务器返回意外的响应,则进入catch6+ .catch(err => { console.log('err:'); console.log(err); }); };
3.设置请求参数
async function btn2() { let url = new URL('http://localhost:5000/test/g2'); url.searchParams.set('a', 3); url.searchParams.set('str', 'abc'); let res = await fetch(url); if (!res.ok) { throw new Error('错误'); } let data = await res.text(); console.log(data); }
4.添加头部信息
async function btn1() { let heard=new Headers(); heard.set('key','value1'); let res = await fetch('http://localhost:5000/test/g1',{headers:heard}); if (!res.ok) { throw new Error('错误'); } let data = await res.text(); console.log(data); }
5.指定请求方式和请求体
async function btn1() { let res = await fetch('http://localhost:5000/test/p3', { method: "post", headers: new Headers({ "Content-Type": "application/json" }), body: JSON.stringify ({ "age": 18, "name": "tom" }) }); if (!res.ok) { throw new Error('错误'); } let data = await res.json(); console.log(data); }
6.解析响应
7.流式访问响应体
8.上传文件
9.跨域请求
10.中断请求
11.其他请求选项