js 通过 fetch 请求数据

fetch是一种原生 js 对 HTTP 数据请求的方式,是 XMLHttpRequest 的一种更理想的替代方案
Fetch API 提供了一个 JavaScript 接口,用于访问和操纵 HTTP 管道的一些具体部分,例如请求和响应,它还提供了一个全局 fetch() 方法,该方法提供了一种简单,合理的方式来跨网络异步获取资源

fetch()请求返回一个包含响应结果的promise(resolve 时会传 Response 对象),它只是一个 HTTP 响应,而不是真的 JSON,为了获取 JSON 的内容,我们需要使用 json()方法(在 Body mixin 中定义,被 Request 和 Response 对象实现)

使用例子:
一般请求:

fetch(url, {
    
    
  method: "POST",
  body: JSON.stringify(data),
  headers: {
    
    
    "Content-Type": "application/json"
  },
  credentials: "same-origin"
}).then(function(response) {
    
    
  response.status     //=> number 100–599
  response.statusText //=> String
  response.headers    //=> Headers
  response.url        //=> String

  return response.json()
}.then(data => {
    
    
	//转换后返回的数据
 	console.log(data)
}).catch(err => {
    
    
	//请求的错误处理
 	console.log(err)
})

HTML

fetch('/users.html')
  .then(function(response) {
    
    
    return response.text()
  }).then(function(body) {
    
    
    document.body.innerHTML = body
  })

JSON

fetch('/users.json')
  .then(function(response) {
    
    
    return response.json()
  }).then(function(json) {
    
    
    console.log('parsed json', json)
  }).catch(function(ex) {
    
    
    console.log('parsing failed', ex)
  })

fetch()方法的两个参数:
url:必须参数,请求的 URL
init:可选参数,请求的配置对象,配置包括

  • method:请求使用的方法,如 GET、POST、PUT,、DELETE、HEAD
  • headers:请求的头信息,形式为 Headers 的对象或包含 ByteString 值的对象字面量
  • body:请求的参数,可能是一个 Blob、BufferSource、FormData、URLSearchParams 或者 USVString 对象,注意 GET 或 HEAD 方法的请求不能包含 body 信息
  • mode:请求是否允许跨域
    • cors:默认值,允许跨域请求,遵守 CORS 协议
    • no-cors:允许来自 CDN 的脚本、其他域的图片和其他一些跨域资源,前提条件是请求的 method 只能是 HEAD、GET 或 POST,而且 js 不能访问 Response 对象中的任何属性
    • same-origin:不允许跨域请求
  • credentials:请求是否携带cookie
    • omit:默认值,不携带cookie
    • same-origin:同源请求下携带cookie
    • include:同源和跨域请求下都携带cookie
  • cache:请求的缓存模式,可能为以下值之一:default 、 no-store 、 reload 、 no-cache 、 force-cache 或者 only-if-cached
  • redirect:请求的重定向方式
    • follow:Chrome 47之前的默认值,自动重定向
    • error:如果产生重定向将自动终止并且抛出一个错误
    • manual:Chrome 47开始的默认值,手动处理重定向
  • referrer:请求的引用者,默认是 client,可以是 no-referrer、client 或一个 URL
  • referrerPolicy:指定了 HTTP 头部 referer 字段的值,可能为以下值之一: no-referrer、 no-referrer-when-downgrade、 origin、 origin-when-cross-origin、 unsafe-url
  • integrity:包括请求的 subresource integrity 值 ( 例如:sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=)

更多内容请参考:
fetch的使用及和ajax的区别
使用 Fetch

猜你喜欢

转载自blog.csdn.net/document_dom/article/details/108051201