0
点赞
收藏
分享

微信扫一扫

Ajax&Fetch学习笔记 08、Fetch



文章目录

  • ​​前言​​
  • ​​一、认识Fetch​​
  • ​​1.1、介绍Fetch​​
  • ​​1.2、Fetch初次使用(查看response)​​
  • ​​二、Fetch使用​​
  • ​​2.1、使用Fetch()来得到响应数据(默认GET请求)​​
  • ​​2.2、Fetch()中的第二个参数(配置fetch)​​

前言

本篇博客是介绍Fetch的使用,若文章中出现相关问题,请指出!

所有博客文件目录索引:博客目录索引(持续更新)

一、认识Fetch

1.1、介绍Fetch

​Fetch​​也是前后端通信的一种方式。

优点:Fetch是Ajax(XMLHttpRequest)的一种替代方案,默认就是基于Promise。

如今不使用Fetch原因:①兼容性问题。②没有abort、timeout机制。③不能通过请求头来携带数据。(只能自己在url上加),还没有很完善所以还在使用ajax。


1.2、Fetch初次使用(查看response)

我们来看一下response的结果内容:

<script>
const url = "https://www.imooc.com/api/http/search/suggest?word=ajax"; //后端对于application/json没有处理,只响应application/x-www-form-urlencoded的get请求

console.log(fetch);

// 发送请求
fetch(url)
.then(response => {
console.log(response);
}).catch(error => {
console.log(error);
})
</script>

Ajax&Fetch学习笔记 08、Fetch_get请求


二、Fetch使用

2.1、使用Fetch()来得到响应数据(默认GET请求)

使用​​Fetch​​来发送请求响应数据:

​data.json​

{
"code": 200,
"data": {
"name": "changlu",
"age": 18
}
}

​index.html​

<script>
//传入url,默认为GET请求
fetch('./data.json').then(function (response) {
console.log(response);
//若是ok为true,表示可以读取数据,就不需要去判断HTTP状态码了
if (response.ok) {
return response.json();//必须要通过调用json()方法得到一个Promise,紧接着继续执行then()方法就能够拿到响应数据
}
}).then(data => { //拿到parse()后的对象
console.log(data);
}).catch(function (error) {
console.log(error);
});

</script>

注意:其中的​​response.json()​​只能调用一次,否则会报错!

Ajax&Fetch学习笔记 08、Fetch_前端_02


2.2、Fetch()中的第二个参数(配置fetch)

配置​​fetch​​​内容是写在一个​​{}​​中的,写于第二个参数:

{
body: JSON.stringify({username:'changlu'}) //body就是请求体,能够传递字符串以及FormData
headers: { //请求头
'Content-Type': 'applicaiton/json' //这里还可以设置其他类型
},
mode: 'cors',//跨域
credentials: 'include' //跨域携带cookie
}

说明

1、若是你设置指定的body为字符串时,可能是key=value&key1=value1或json字符串都要记得设置指定的Content-Type;若是传递FormData的话可以不设置,其默认会设置为

示例:测试FormData作为请求体

<script>
// const url = "https://www.imooc.com/api/http/json/search/suggest?word=ajax"; //后端对于application/json处理过的接口
const url = "https://www.imooc.com/api/http/search/suggest?word=ajax"; //后端对于application/json没有处理,只响应application/x-www-form-urlencoded的get请求

console.log(fetch);

// 发送请求
const formdata = new FormData();
formdata.append("username", "changlu");
formdata.append("age", 18);
// 发送请求
fetch(url, {
method: 'POST',
body: formdata //fetch默认会设置Content-Type: multipart/form-data;
})
.then(response => {
if (response.ok) {
return response.json();
}
}).then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
})
</script>

Ajax&Fetch学习笔记 08、Fetch_数据_03

Ajax&Fetch学习笔记 08、Fetch_数据_04

可以看到内容类型默认设置​​multpart/form-data​​,你可以进行额外其他设置。



我是长路,感谢你的耐心阅读。如有问题请指出,我会积极采纳!
欢迎关注我的公众号【长路Java】,分享Java学习文章及相关资料
Q群:851968786 我们可以一起探讨学习
注明:转载可,需要附带上文章链接




举报

相关推荐

0 条评论