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

Using Fetch to make http requests

php中世界最好的语言
Release: 2018-03-13 16:01:17
Original
2969 people have browsed it

This time I will bring you the precautions on using Fetch to make http requests. The following is a practical case. Let’s take a look.

Traditional Ajax uses XMLHttpRequest (XHR) to send requests to obtain data, without paying attention to the principle of separation. The Fetch API is designed based on Promise and is designed to solve XHR problems.

XMLHttpRequest is a poorly designed API with very confusing configuration and calling methods.
Use XHR to send a json request:

var xhr = new XMLHttpRequest();
xhr.open('GET',url);
xhr.responseType = 'json';
xhr.onload = function(){    console.log(xhr.response);
}
xhr.onerror = function(){    console.log('xhr error');
}
xhr.send();
Copy after login

After using fetch to make the request:

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

es6 writing method:

fetch(url).then(response=>response.json())
    .then(data=>console.log(data))
    .catch(e=>console.log('error' + e));
Copy after login

Process text/html response:

fetch(url).then(response=>response.text())
    .then(data=>console.log(data))
    .catch(e=>console.log('error' + e));
Copy after login

Get header information:

fetch(url).then((response)=>{    console.log(response.status);    console.log(response.statusText);    console.log(response.headers.get('Content-Type'));    console.log(response.headers.get('Date'));    return response.json();
}).then(data=>console.log(data))
  .catch(e=>console.log('error' + e);
Copy after login

Set header information

fetch(url,{    headers:{        'Accept': 'application/json',        'Content-Type': 'application/json'
    }
}).then(response=>response.json())
  .then(data=>console.log(data))
  .catch(e=>console.log('error' + e);
Copy after login

Submit form

fetch(url,{    method: 'post',    body: new FormData(document.getElementById('form'))
}).then(response=>response.json())
  .then(data=>console.log(data))
  .catch(e=>console.log('error' + e);
Copy after login

Submit json data

fetch(url,{    method: 'post',    body: JSON.stringify({        username: document.getElementById('username').value,        password: document.getElementById('password').value
    })
}).then(response=>response.json())
  .then(data=>console.log(data))
  .catch(e=>console.log('error' + e);
Copy after login

fetch features

Simple syntax, more semantic

Based on standard Promise implementation, supports async/await

Convenient isomorphism, compatible with isomorphic-fetch

fetch Performance

Browser compatibility

fetch’s native support is not high, but some polyfills can be used.

IE8 is es3 syntax and needs to introduce es5 polyfill: es5-shim

Support promise syntax: es6-promise

fetch polyfill: fetch-polyfill

To use jsonp, you also need to introduce: fetch-jsonp

Enable babel's runtime mode, you can use async/await

fetchFAQ

fetch The request does not include cookies by default. You need to set fetch(url,{credentials: 'include'});

The server will not reject if it returns 400 or 500 error codes. Only network error requests will not be rejected. It will be rejected only when it is completed;

Summary

The fetch API seems simple, but it is an improvement brought about by the continuous enhancement and improvement of js syntax.
Since various libraries are generally introduced in projects to solve underlying problems, they do not pay much attention to the addition and expansion of basic APIs. Over time, they will develop a sense of separation from standards. In the future, we should pay more attention to the changes and basic implementation of the underlying API.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

CSS usage in React.js

async/await in JS

The above is the detailed content of Using Fetch to make http requests. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!