温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JavaScript中使用Fetch()的案例

发布时间:2020-10-10 18:01:14 来源:亿速云 阅读:202 作者:小新 栏目:web开发

这篇文章主要介绍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));
上传文件

使用 <input type="file" />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()的案例的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI