若是看网上的fetch教程,会首先对比XMLHttpRequest和fetch的优劣,而后引出一堆看了很快会忘记的内容(本人记性很差)。所以,我写一篇关于fetch的文章,为了本身看着方便,毕竟工做中用到的也就是一些很基础的点而已。html
fetch,说白了,就是XMLHttpRequest的一种替代方案。若是有人问你,除了Ajax获取后台数据以外,还有没有其余的替代方案?json
这是你就能够回答,除了XMLHttpRequest对象来获取后台的数据以外,还可使用一种更优的解决方案fetch。后端
// 经过fetch获取百度的错误提示页面 fetch('https://www.baidu.com/search/error.html') // 返回一个Promise对象 .then((res)=>{ return res.text() // res.text()是一个Promise对象 }) .then((res)=>{ console.log(res) // res是最终的结果 })
完成了helloworld,这个时候就要来认识一下GET请求如何处理了。浏览器
上面的helloworld中这是使用了第一个参数,其实fetch还能够提供第二个参数,就是用来传递一些初始化的信息。cookie
这里若是要特别指明是GET请求,就要写成下面的形式:app
// 经过fetch获取百度的错误提示页面 fetch('https://www.baidu.com/search/error.html', { method: 'GET' }) .then((res)=>{ return res.text() }) .then((res)=>{ console.log(res) })
GET请求中若是须要传递参数怎么办?这个时候,只能把参数写在URL上来进行传递了。学习
// 经过fetch获取百度的错误提示页面 fetch('https://www.baidu.com/search/error.html?a=1&b=2', { // 在URL中写上传递的参数 method: 'GET' }) .then((res)=>{ return res.text() }) .then((res)=>{ console.log(res) })
与GET请求相似,POST请求的指定也是在fetch的第二个参数中:fetch
// 经过fetch获取百度的错误提示页面 fetch('https://www.baidu.com/search/error.html', { method: 'POST' // 指定是POST请求 }) .then((res)=>{ return res.text() }) .then((res)=>{ console.log(res) })
众所周知,POST请求的参数,必定不能放在URL中,这样作的目的是防止信息泄露。ui
// 经过fetch获取百度的错误提示页面 fetch('https://www.baidu.com/search/error.html', { method: 'POST', body: new URLSearchParams([["foo", 1],["bar", 2]]).toString() // 这里是请求对象 }) .then((res)=>{ return res.text() }) .then((res)=>{ console.log(res) })
在POST提交的过程当中,通常是表单提交,但是,通过查询,发现默认的提交方式是:Content-Type:text/plain;charset=UTF-8,这个显然是不合理的。下面我们学习一下,指定头信息:url
// 经过fetch获取百度的错误提示页面 fetch('https://www.baidu.com/search/error.html', { method: 'POST', headers: new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' // 指定提交方式为表单提交 }), body: new URLSearchParams([["foo", 1],["bar", 2]]).toString() }) .then((res)=>{ return res.text() }) .then((res)=>{ console.log(res) })
这个时候,在谷歌浏览器的Network中查询,会发现,请求方式已经变成了content-type:application/x-www-form-urlencoded。
上面全部的例子中都是返回一个文本,那么除了文本,有没有其余的数据类型呢?确定是有的,具体查询地址:Body的类型
因为最经常使用的是JSON数据,那么下面就简单演示一下获取JSON数据的方式:
fetch('https://www.baidu.com/rec?platform=wise&ms=1&rset=rcmd&word=123&qid=11327900426705455986&rq=123&from=844b&baiduid=A1D0B88941B30028C375C79CE5AC2E5E%3AFG%3D1&tn=&clientWidth=375&t=1506826017369&r=8255', { // 在URL中写上传递的参数 method: 'GET', headers: new Headers({ 'Accept': 'application/json' // 经过头指定,获取的数据类型是JSON }) }) .then((res)=>{ return res.json() // 返回一个Promise,能够解析成JSON }) .then((res)=>{ console.log(res) // 获取JSON数据 })
默认状况下, fetch 不会从服务端发送或接收任何 cookies, 若是站点依赖于维护一个用户会话,则致使未经认证的请求(要发送 cookies,必须发送凭据头).
// 经过fetch获取百度的错误提示页面 fetch('https://www.baidu.com/search/error.html', { method: 'GET', credentials: 'include' // 强制加入凭据头 }) .then((res)=>{ return res.text() }) .then((res)=>{ console.log(res) })