Learn fetch and start here

Keywords: Javascript Front-end api fetch

1, What is fetch()?

fetch() is the browser's built-in global JavaScript method. It is used to issue http requests. It can be used directly without downloading and installing.

// A simple http request
fetch('http://example.com/movies.json')
    .then(function (response) {
        return response.json();
    })
    .then(function (myJson) {
        console.log(myJson);
    });
2, How to use it?
1. Simple use example

The second parameter of fetch() is the init object, which is used to set the configuration information of http.

postData('http://example.com/answer', { answer: 42 })
    .then(data => console.log(data))
    .catch(error => console.error(error))

function postData(url, data) {
    return fetch(url, {
        body: JSON.stringify(data),
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            'user-agent': 'Mozilla/4.0 MDN Example',
            'content-type': 'application/json'
        },
        method: 'POST',
        mode: 'cors',
        redirect: 'follow',
        referrer: 'no-referrer',
    })
        .then(response => response.json())
}
2. Configuration details
  • Method: the method used in the request, such as GET, POST, PUT, DELETE, etc.
  • headers: header information of the request.
  • Body: the body information of the request. Note that the request of GET or HEAD methods cannot contain body information.
  • Mode: request mode. Available values: cors, no cors, and same origin
  • credentials: whether to send cookies to the server: omit (never send cookies in any case), same origin (only send cookies in the same source), include (send cookies in any case)
  • Cache: available cache modes: default, no store, reload, no cache, force cache, and only if cached.
  • Redirect: redirect. follow is used by default in Chrome;
    • follow (auto redirect)
    • Error (redirection will automatically terminate and throw an error)
    • manual (handle redirection manually)
  • Referrer: the URL of the page sending the request. The browser is added to the request Header by default. Set to no referrer to indicate no addition.
  • Referrpolicy: when to use referrer. Available values: no referrer, no referrer when downgrade, origin, origin when cross origin, unsafe URL.
  • Integrity: set the hash value corresponding to the resource to ensure the integrity of the resource.
3, Usage scenario
1. Send request with credentials
// Requests with credentials will be sent from the same source but not from the same source
fetch('https://example.com', {
  credentials: 'include'
})

// Only the same source sends a request with credentials
fetch('https://example.com', {
  credentials: 'same-origin'
})

// Requests without credentials are sent from the same source but not from the same source
fetch('https://example.com', {
  credentials: 'omit'
})
2. 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));
3. Upload file

You can upload files through HTML < input type = "file" / > elements, FormData objects, and fetch() methods.

var formData = new FormData();
var fileField = document.querySelector("input[type='file']");

formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);

fetch('https://example.com/profile/avatar', {
  method: 'PUT',
  body: formData
})
.then(response => response.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
4. Upload multiple files

You can upload files through HTML < input type = "file" multiple / > elements, FormData() and fetch().

var formData = new FormData();
var photos = document.querySelector("input[type='file'][multiple]");

formData.append('title', 'My Vegas Vacation');
// formData only accepts files, blobs or strings, and cannot directly pass arrays, so it must be embedded circularly
for (let i = 0; i < photos.files.length; i++) {
    formData.append('photo', photos.files[i]);
}

fetch('https://example.com/posts', {
  method: 'POST',
  body: formData
})
.then(response => response.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));
5. Check whether the request is successful

The following methods can be used to capture network failures and server-side CORS restricted errors for further processing (for example, logging, etc.).

fetch('flowers.jpg').then(function (response) {
    if (response.ok) {
        return response.blob();
    }
    throw new Error('Network response was not ok.');
}).then(function (myBlob) {
    var objectURL = URL.createObjectURL(myBlob);
    myImage.src = objectURL;
}).catch(function (error) {
    console.log('There has been a problem with your fetch operation: ', error.message);
});
6. Create a new Request and send an http Request
var myHeaders = new Headers();

var myInit = {
    method: 'GET',
    headers: myHeaders,
    mode: 'cors',
    cache: 'default'
};

var myRequest = new Request('flowers.jpg', myInit);

fetch(myRequest).then(function (response) {
    return response.blob();
}).then(function (myBlob) {
    var objectURL = URL.createObjectURL(myBlob);
    myImage.src = objectURL;
});
4, Headers
1. Create Headers object
// FA Yi
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");

// Method II
myHeaders = new Headers({
    "Content-Type": "text/plain",
    "Content-Length": content.length.toString(),
    "X-Custom-Header": "ProcessThisImmediately",
});
2. Method of Headers object

The Headers object provides methods for reading, setting, and judging.

console.log(myHeaders.has("Content-Type")); // true
console.log(myHeaders.has("Set-Cookie")); // false
myHeaders.set("Content-Type", "text/html");
myHeaders.append("X-Custom-Header", "AnotherValue");

console.log(myHeaders.get("Content-Length")); // 11
console.log(myHeaders.getAll("X-Custom-Header")); // ["ProcessThisImmediately", "AnotherValue"]

myHeaders.delete("X-Custom-Header");
console.log(myHeaders.getAll("X-Custom-Header")); // [ ]
3. Attribute error

Setting unsupported properties in Headers will report an error.

var myResponse = Response.error();
try {
    myResponse.headers.set("Origin", "http://mybank.com");
} catch (e) {
    console.log("Cannot pretend to be a bank!");
}
4. Data format confirmation

After obtaining the data, check the data format first, and conduct further processing after meeting the expected format.

fetch(myRequest).then(function (response) {
    if (response.headers.get("content-type") === "application/json") {
        return response.json().then(function (json) {
            // Further data processing
        });
    } else {
        console.log("Oops, we haven't got JSON!");
    }
});
5. guard attribute

The Headers object can be used in request sending and response receiving. It has a guard attribute to indicate that those parameters are read-only.

  • none: default
  • Request: the headers (Request.headers) obtained from the request are read-only
  • Request no CORS: read only headers obtained from requests from different domains (request. Mode no CORS)
  • Response: the headers obtained from the response (Response.headers) are read-only
  • immutable: the most commonly used in service workers. All headers are read-only.
6,Content-Type

Both request and response (including the fetch() method) try to set the content type automatically. If the content type value is not set, the sent request will also be set automatically.

5, Response object

After a fetch sends a request, the Response object is returned. Its common properties are:

  • Response.status: integer (the default value is 200) is the status code of response.
  • Response.statusText: string (the default value is "OK"), which corresponds to the HTTP status code message.
  • Response.ok: this attribute is used to check whether the response status is in the range of 200 - 299 (including 200 and 299). This property returns a Boolean value.
6, body object

Both Request and Response can have body objects. Both Request and Response objects implement the following methods to obtain the contents of body in different formats: arrayBuffer(), blob(), json(), text(), formData()

7, Check whether the fetch is available?
if(self.fetch) {
    // run my fetch request here
} else {
    // do something with XMLHttpRequest?
}
8, Other
1. Differences between fetch and jQuery.ajax()
  • When fetch() receives an HTTP status code representing an error (such as 404 or 500), it will set the resolve value of Promise to false, but will not reject. It will reject only if the network fails or the request is blocked.

  • fetch() can accept cross domain cookies and establish cross domain sessions.

  • fetch() will send cookies only if the credentials option is used, but it must comply with the same origin rule.

2. The difference between fetch and axios

Details, look here!

3. CORS (cross domain access) error
/* Error:
  Access to fetch at '×××'
  from origin '×××' has been blocked by CORS policy: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. If an opaque response serves your needs, set the request's
  mode to 'no-cors' to fetch the resource with CORS disabled.
*/

For cross domain access, see here!

9, Reference documents

Posted by snowrhythm on Wed, 24 Nov 2021 08:36:22 -0800