×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Javascript
Posted by: Isaac Dettman
Added: Nov 4, 2016 9:51 PM
Modified: Nov 4, 2016 10:26 PM
Views: 14
javascript fetch examples
  1. var result = fetch('https://api.github.com')
  2.     result.then(function(response) {
  3.       console.log('response', response)
  4.       console.log('header', response.headers.get('Content-Type'))
  5.       return response.text()
  6.     }).then(function(text) {
  7.       console.log('got text', text)
  8.     }).catch(function(ex) {
  9.       console.log('failed', ex)
  10.     })
  11.  
  12.  
  13. var myImage = document.querySelector('img');
  14.  
  15. fetch('flowers.jpg')
  16. .then(function(response) {
  17.   return response.blob();
  18. })
  19. .then(function(myBlob) {
  20.   var objectURL = URL.createObjectURL(myBlob);
  21.   myImage.src = objectURL;
  22. });  
  23.  
  24.  
  25.  
  26. // Request options
  27. var myHeaders = new Headers();
  28.  
  29. var myInit = { method: 'GET',
  30.                headers: myHeaders,
  31.                mode: 'cors',
  32.                cache: 'default' };
  33.  
  34. fetch('flowers.jpg',myInit)
  35. .then(function(response) {
  36.   return response.blob();
  37. })
  38. .then(function(myBlob) {
  39.   var objectURL = URL.createObjectURL(myBlob);
  40.   myImage.src = objectURL;
  41. });
  42.  
  43. // Check for success
  44. fetch('flowers.jpg').then(function(response) {
  45.   if(response.ok) {
  46.     response.blob().then(function(myBlob) {
  47.       var objectURL = URL.createObjectURL(myBlob);
  48.       myImage.src = objectURL;
  49.     });
  50.   } else {
  51.     console.log('Network response was not ok.');
  52.   }
  53. })
  54. .catch(function(error) {
  55.   console.log('There has been a problem with your fetch operation: ' + error.message);
  56. });
  57.  
  58. // Supply request object
  59. var myHeaders = new Headers();
  60.  
  61. var myInit = { method: 'GET',
  62.                headers: myHeaders,
  63.                mode: 'cors',
  64.                cache: 'default' };
  65.  
  66. var myRequest = new Request('flowers.jpg', myInit);
  67.  
  68. fetch(myRequest)
  69. .then(function(response) {
  70.   return response.blob();
  71. })
  72. .then(function(myBlob) {
  73.   var objectURL = URL.createObjectURL(myBlob);
  74.   myImage.src = objectURL;
  75. });
  76.  
  77.  
  78. // Create Headers object
  79. var content = "Hello World";
  80. var myHeaders = new Headers();
  81. myHeaders.append("Content-Type", "text/plain");
  82. myHeaders.append("Content-Length", content.length.toString());
  83. myHeaders.append("X-Custom-Header", "ProcessThisImmediately");
  84.  
  85. // or
  86. myHeaders = new Headers({
  87.   "Content-Type": "text/plain",
  88.   "Content-Length": content.length.toString(),
  89.   "X-Custom-Header": "ProcessThisImmediately",
  90. });
  91.  
  92. // read Headers values
  93. console.log(myHeaders.has("Content-Type")); // true
  94. console.log(myHeaders.has("Set-Cookie")); // false
  95. myHeaders.set("Content-Type", "text/html");
  96. myHeaders.append("X-Custom-Header", "AnotherValue");
  97.  
  98. console.log(myHeaders.get("Content-Length")); // 11
  99. console.log(myHeaders.getAll("X-Custom-Header")); // ["ProcessThisImmediately", "AnotherValue"]
  100.  
  101. myHeaders.delete("X-Custom-Header");
  102. console.log(myHeaders.getAll("X-Custom-Header")); // [ ]
  103.  
  104. // Check Headers content type before further processing
  105. fetch(myRequest).then(function(response) {
  106.   var contentType = response.headers.get("content-type");
  107.   if(contentType && contentType.indexOf("application/json") !== -1) {
  108.     return response.json().then(function(json) {
  109.       // process your JSON further
  110.     });
  111.   } else {
  112.     console.log("Oops, we haven't got JSON!");
  113.   }
  114. });
  115.  
  116. // Response object
  117. var myBody = new Blob();
  118.  
  119. addEventListener('fetch', function(event) {
  120.   event.respondWith(
  121.     new Response(myBody, {
  122.       headers: { "Content-Type" : "text/plain" }
  123.     })
  124.   );
  125. });
  126.