- Fetch 优点主要有:
-
1. 语法简洁,更加语义化,业务逻辑更清晰2. 基于标准 Promise 实现,支持 async/await3. 同构方便,使用isomorphic-fetch
- Fetch请求本地的数据
- 本地有一个test.txt文档,通过以下代码就可以获取其中的数据,并且显示在页面上。
-
document.getElementById('button1').addEventListener('click',getText);function getText(){fetch("test.txt").then((res) => res.text())//注意:此处是res.text().then(data => {console.log(data);document.getElementById('output').innerHTML = data;}).catch(err => console.log(err));}
-
Fetch请求本地的json文件
-
本地有个posts.json数据,与请求本地文本不同的是,得到数据后还要用forEach遍历,最后呈现在页面上。document.getElementById('button2').addEventListener('click',getJson);function getJson(){fetch("posts.json").then((res) => res.json()).then(data => {console.log(data);let output = '';data.forEach((post) => {output += `<li>${post.title}</li>`;})document.getElementById('output').innerHTML = output;}).catch(err => console.log(err));}
-
fetch请求api
-
获取 https://api. github.com/users中的数据,做法与获取本地JSON的方法类似,得到数据后,同样要经过处理document.getElementById('button3').addEventListener('click',getExternal);function getExternal(){fetch("https://api.github.com/users").then((res) => res.json()).then(data => {console.log(data);let output = '';data.forEach((user) => {output += `<li>${user.login}</li>`;})document.getElementById('output').innerHTML = output;}).catch(err => console.log(err));}
*注意:
Fetch会返回Promise,所以在获取资源后,可以使用.then方法做你想做的。
.then(response => {/* do something */})
如果这是你第一次遇见Fetch,也许惊讶于Fetch返回的response。如果console.log返回的response,会得到下列信息:
{
body: ReadableStream
bodyUsed: false
headers: Headers
ok : true
redirected : false
status : 200
statusText : "OK"
type : "cors"
url : "http://some-website.com/some-url"
__proto__ : Response
}
可以看出Fetch返回的响应能告知请求的状态。从上面例子看出请求是成功的(ok是true,status是200),但是我们想获取的仓库名却不在这里。
所有这些方法(response.json等等)返回另一个Promise,所以可以调用.then方法处理我们转换后的数据。
.then(response => response.json())
.then(data => {
// data就是我们请求的repos
console.log(data)
});
可以看出Fetch获取数据方法简短并且简单。
-
- fetch发送数据
-
- 使用Fetch发送也很简单,只需要配置三个参数。
-
- 第一个参数是设置请求方法(如post、put或del),Fetch会自动设置方法为get。
-
第二个参数是设置头部。因为一般使用JSON数据格式,所以设置ContentType为application/json。
-
第三个参数是设置包含JSON内容的主体。因为JSON内容是必须的,所以当设置主体时会调用JSON.stringify。
- Post请求一般的方法:
-
- let content = {some: 'content'};
-
fetch('some-url', {method: 'post',headers: {'Content-Type': 'application/json'},body: JSON.stringify(content)}).then(res=>res.json).then(res=>console.log(res))
2万+

被折叠的 条评论
为什么被折叠?



