The fetch profile

  • The Fetch API provides a JavaScript interface for accessing and manipulating specific parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method, which provides a simple, reasonable way to fetch resources asynchronously across a network.
  • This functionality was previously implemented using XMLHttpRequest. Fetch provides a more desirable alternative that can be easily used by other technologies, such as Service Workers (EN-US). Fetch also provides dedicated logical space to define other HTTP-related concepts, such as CORS and HTTP extensions.

The FETCH specification differs from jquery.Ajax () in three main ways

When an HTTP status code representing an error is received, the Promise returned from fetch() is not marked as reject, even if the HTTP status code of the response is 404 or 500. Instead, it marks the Promise state as resolve (but sets the OK attribute of the return value of Resolve to false), and only as Reject when the network fails or the request is blocked.
Fetch () can not accept cross-domain cookies; You can also set up a cross-domain session without using fetch(). Set-cookie header fields of other sites will be ignored.
Fetch does not send cookies. Unless you use the initialization option for credentials. After August 25, 2017, the default credentials policy is changed to same-Origin. Firefox has also been modified in version 61.0b13)

———— the above differences from the official website

In my opinion, it has a clearer structure than Ajax. In THEN, response is processed first and then, and data JSON formatting is provided inside (Response.json ()). Another thing that makes it more object-oriented is that a Request /Headers can instantiate the object and configure its properties. Such as:


var myHeaders = new Headers();

myHeaders.append("Content-Type", "text/plain");

Copy the code
Response also provides a richer API:

Fetch is used in non-browser Settings

If you want to use Fetch in unsupported browsers, you can use Fetch Polyfill, which is the typescripe standard and can be used by downloading NPM to install the Fetch environment

Browser compatibility

To encapsulate the fetch

Call the wrapped FETCH

This section found that the response body returned must be in JSON format, and simple string values and so on would cause problems

/ / get a list of information function getList () {F_Request. GetRequest (' http://localhost:8080/list ', null, function(data) { document.getElementById("content").innerText = JSON.stringify(data); console.log(data); }, function(error) { console.log(error); }); } / request/upload function uploadFile () {/ / upload file name value is contain parameter values F_Request uploadFileRequest (" upload ", "file", {the userName: 'bill', age: 15}, "http://localhost:8080/uploadMul", null, the function (data) {the console. The log (" upload success: "); console.log(data); }, function(error) {console.log(" upload failed "); }); }Copy the code

Personally wrapped FETCH (GET and POST requests have been validated, including multiple file uploads, as well as some Java backend code)

var F_Request = { getRequest: Function (URL, initParams, successFunc = null, errorFunc = null) {/** * get request */ initParams = initParams? initParams : {}; initParams = Object.assign(initParams, { method: "GET" }); this.RequestData(url, initParams, successFunc, errorFunc); }, postRequest: function(url, initParams, successFunc = null, errorFunc = null) { initParams = initParams ? initParams : {}; initParams = Object.assign(initParams, { method: "POST" }); this.RequestData(url, initParams, successFunc, errorFunc); }, putRequest: function(url, initParams, successFunc = null, errorFunc = null) {//put request initParams = initParams? initParams : {}; initParams = Object.assign(initParams, { method: "PUT" }); this.RequestData(url, initParams, successFunc, errorFunc); }, uploadFileRequest: function(fileName = "upload", fileKey = "file", otherParams = {}, url, initParams, successFunc = null, ErrorFunc = null) {var formData = new formData (); var photos = document.querySelector("input[name='" + fileName + "'][multiple]"); for (var param in otherParams) { formData.append(param, otherParams[param]); } // formData only accepts files, blobs, or strings. It cannot pass arrays directly, so it must loop in for (let I = 0; i < photos.files.length; i++) { formData.append(fileKey, photos.files[i]); } initParams = initParams ? initParams : {}; initParams.body = formData; initParams.method = initParams.method ? initParams.method : "POST"; this.postRequest(url, initParams, successFunc, errorFunc); }, deleteRequest: Function (URL, initParams, successFunc = null, errorFunc = null) {** * delete request */ initParams = initParams? initParams : {}; initParams = Object.assign(initParams, { method: "DELETE" }); this.RequestData(url, initParams, successFunc, errorFunc); }, RequestData: Function (url, initParams, successFunc = null, errorFunc = null) {/** */ var defaultInitParams = {cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached credentials: 'same-origin', // include, *omit /* headers: {'user-agent': Mozilla/4.0 MDN Example, 'content-type': 'application/json'}, */ method: 'GET', // *GET, POST, PUT, DELETE, etc. //mode: 'cors', // no-cors, cors, *same-origin redirect: 'follow', // manual, *follow, error referrer: 'no-referrer', // *client, no-referrer }; / / if the request method to GET and HEAD is to remove the body information if (defaultInitParams. Method = = 'GET' | | defaultInitParams. Method = = 'HEAD') {delete defaultInitParams.method; } if (initParams.method == 'GET' || initParams.method == 'HEAD') { delete initParams.method; } defaultInitParams = Object.assign(defaultInitParams, initParams); fetch( url, If (response.status === 200) {return response.json(); } return { error: 300 }; }). Then (function(response) {if (response.error == 300) {console.log("-- please check the fetch configuration is wrong --"); return; } if (typeof(successFunc) == "function") { successFunc(response); } }).catch(function(error) { if (typeof(errorFunc) == "function") { errorFunc(error) } }); }}Copy the code

[Full code](gitee.com/ten-ken/sty…

Welcome to pay attention to my public number: programmer Ken, the path of the program, let us explore together, common progress.