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.
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.
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(url).then(function(response) { return response.json(); }).then(function(data) { console.log(data); }).catch(function(e) { console.log("Oops, error"); });
Use arrow functions:
fetch(url).then(response => response.json()) .then(data => console.log(data)) .catch(e => console.log("Oops, error", e))
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() 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 }
Requests containing credentials:
fetch('https://example.com', { //将credentials: 'include'添加到传递给fetch()方法的init对象 credentials: 'include' })
If credentials are sent from the same origin:
fetch('https://example.com', { credentials: 'same-origin' })
Make sure the browser is not included in the request Contain credentials:
fetch('https://example.com', { credentials: 'omit' })
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));
Use<input type="file" />
, FormData()
and fetch()
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");
Content can be obtained:
console.log(myHeaders.has("Content-Type")); // true console.log(myHeaders.has("Set-Cookie")); // false
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!