成都创新互联网站制作重庆分公司

JavaScript中使用Fetch()的案例-创新互联

这篇文章主要介绍JavaScript中使用Fetch()的案例,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:主机域名网站空间、营销软件、网站建设、城中网站维护、网站推广。

Fetch()提供了一种方式进行跨网络异步请求资源的方式,用于访问和操作HTTP管道的部分,比如:请求和相应。

fetch常见的坑:
  • 接收到表示错误的HTTP状态码时,fetch()返回的Promise不会被标记为reject(即使状态码为404或500)。fetch()会将Promise状态标记为resolve(但resolve返回值但OK 属性设置为 false)。网络故障或请求被阻止才会标记为reject。

  • fetch()不会从服务端发送或接收任何cookies。发送cookies 需要设置 fetch(url, {credentials: 'include'}) 选项。

原始XHR请求
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';

xhr.onload = function() {
  console.log(xhr.response);
};

xhr.onerror = function() {
  console.log("Oops, error");
};

xhr.send();
fetch请求
fetch(url).then(function(response) {
  return response.json();
}).then(function(data) {
  console.log(data);
}).catch(function(e) {
  console.log("Oops, error");
});

使用箭头函数:

fetch(url).then(response => response.json())
  .then(data => console.log(data))
  .catch(e => console.log("Oops, error", e))

获取一个JSON文件,并打印到控制台。指明资源路径,然后返回一个Response对象,使用json()方法获取JSON但内容。

fetch参数

fetch()接受第二个可选参数,控制不同配置的init参数。

// Example POST method implementation:

postData('http://example.com/answer', {answer: 42})
  .then(data => console.log(data)) // JSON from `response.json()` call
  .catch(error => console.error(error))

function postData(url, data) {
  // Default options are marked with *
  return fetch(url, {
    body: JSON.stringify(data), // must match 'Content-Type' header
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, same-origin, *omit
    headers: {
      'user-agent': 'Mozilla/4.0 MDN Example',
      'content-type': 'application/json'
    },
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, cors, *same-origin
    redirect: 'follow', // manual, *follow, error
    referrer: 'no-referrer', // *client, no-referrer
  })
  .then(response => response.json()) // parses response to JSON
}
包含凭据的请求

包含凭据的请求:

fetch('https://example.com', {
    //将credentials: 'include'添加到传递给fetch()方法的init对象
    credentials: 'include' 
})

若在同源橱发送凭据:

fetch('https://example.com', {
  credentials: 'same-origin'  
})

确保浏览器不在请求中包含凭据:

fetch('https://example.com', {
  credentials: 'omit'  
})
上传JSON数据
var url = 'https://example.com/profile';
var data = {username: 'example'};

fetch(url, {
  method: 'POST', // or 'PUT'
  body: JSON.stringify(data), // data can be `string` or {object}!
  headers: new Headers({
    'Content-Type': 'application/json'
  })
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
上传文件

使用FormData()fetch()

Headers

使用Headers构造函数创建headers对象,headers对象为多键值对:

var content = "Hello World";
var myHeaders = new Headers();
myHeaders.append("Content-Type", "text/plain");
myHeaders.append("Content-Length", content.length.toString());
myHeaders.append("X-Custom-Header", "ProcessThisImmediately");

内容可被获取:

console.log(myHeaders.has("Content-Type")); // true
console.log(myHeaders.has("Set-Cookie")); // false
Fetch 优点主要有:
  • 语法简洁,更加语义化

  • 基于标准 Promise 实现,支持 async/await

  • 同构方便,使用 isomorphic-fetch

以上是JavaScript中使用Fetch()的案例的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注创新互联网站制作公司行业资讯频道!


本文名称:JavaScript中使用Fetch()的案例-创新互联
URL标题:http://www.cxhlcq.cn/article/cseepj.html

其他资讯

在线咨询

微信咨询

电话咨询

028-86922220(工作日)

18980820575(7×24)

提交需求

返回顶部