Home > Web Front-end > JS Tutorial > body text

Usage example of Fetch() in JavaScript (code)

不言
Release: 2018-11-21 11:37:01
forward
13576 people have browsed it

The content of this article is about the usage examples (code) of Fetch() in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Fetch() provides a way to asynchronously request resources across the network and is used to access and operate parts of the HTTP pipeline, such as requests and responses.

Common pitfalls of fetch:
  • When receiving an HTTP status code indicating an error, the Promise returned by fetch() will not be marked as reject (even if the status code is 404 or 500). fetch() will mark the Promise state as resolved (but resolve returns a value but the OK property is set to false). Network failure or the request is blocked will be marked as rejected.

  • fetch() does not send or receive any cookies from the server. Sending cookies requires setting the fetch(url, {credentials: 'include'}) option.

Original XHR request

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();
Copy after login

fetch request

fetch(url).then(function(response) {
  return response.json();
}).then(function(data) {
  console.log(data);
}).catch(function(e) {
  console.log("Oops, error");
});
Copy after login

Use arrow functions:

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

Get a JSON file, and print to the console. Specify the resource path, then return a Response object, and use the json() method to obtain the JSON content.

fetch parameter

fetch() accepts a second optional parameter to control the init parameters of different configurations.

// 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
}
Copy after login

Requests containing credentials

Requests containing credentials:

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

If credentials are sent from the same origin:

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

Make sure the browser is not included in the request Contain credentials:

fetch('https://example.com', {
  credentials: 'omit'  
})
Copy after login

Upload JSON data

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));
Copy after login

Upload file

Use<input type="file" />, FormData() and fetch()

Headers

Use the Headers constructor to create headers objects. The headers objects are multi-key value pairs:

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");
Copy after login

Content can be obtained:

console.log(myHeaders.has("Content-Type")); // true
console.log(myHeaders.has("Set-Cookie")); // false
Copy after login

To summarize, the main advantages of Fetch are:

  • Simple syntax and more semantic

  • Based on standard Promise implementation, supports async/await

  • Isomorphic convenience, use isomorphic-fetch

The above is the detailed content of Usage example of Fetch() in JavaScript (code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template