JavaScript中fetch获取后台数据

除了XMLHttpRequest对象来获取后台的数据之外,还可以使用一种更优的解决方案——fetch


㈠fetch示例

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是最终的结果

 })

㈡GET请求

⑴GET请求初步

fetch可以提供第二个参数,就是用来传递一些初始化的信息。

// 通过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)
  })

㈢POST请求

⑴POST请求的指定也是在fetch的第二个参数中:

// 通过fetch获取百度的错误提示页面
fetch('https://www.baidu.com/search/error.html', {
    method: 'POST' // 指定是POST请求
  })
  .then((res)=>{
    return res.text()
  })
  .then((res)=>{
    console.log(res)
  })

⑵POST请求参数的传递

众所周知,POST请求的参数,一定不能放在URL中,这样做的目的是防止信息泄露。

// 通过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,这个显然是不合理的。

指定头信息:

// 通过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。

 

㈣通过接口得到JSON数据

上面所有的例子中都是返回一个文本,还有其他的数据类型,具体查询地址:Body的类型

演示一下获取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数据
  })

㈤强制带Cookie

默认情况下, 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)
  })

参考或转自:http://www.fly63.com/article/detial/1042

原文地址:https://www.cnblogs.com/shihaiying/p/12115691.html