您好,欢迎访问一九零五行业门户网

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));
上传文件使用 <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)); // trueconsole.log(myheaders.has(set-cookie)); // false
总结一下,fetch 优点主要有:语法简洁,更加语义化
基于标准 promise 实现,支持 async/await
同构方便,使用 isomorphic-fetch
以上就是javascript中fetch() 的用法示例(代码)的详细内容。
其它类似信息

推荐信息