当前位置:   article > 正文

js 通过 fetch 请求数据_fetch json

fetch json

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)
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

HTML

fetch('/users.html')
  .then(function(response) {
    return response.text()
  }).then(function(body) {
    document.body.innerHTML = body
  })
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

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)
  })
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

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

ie使用fetch

安装npm插件 whatwg-fetch

npm install whatwg-fetch --save
  • 1

使用

import 'whatwg-fetch'
  • 1

ie8 下需要安装 fetch-ie8

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/正经夜光杯/article/detail/938507
推荐阅读
相关标签
  

闽ICP备14008679号