What is Fetch?
Fetch is used to replace the traditional XMLHttpRequest. It has many advantages, including the syntax of chained calls, the return of promise, and so on.
The fetch API is based on the promise design, which is intended to replace the unreasonable wording of the traditional xhr.
Traditional XMLHttpRequest requests are busy, and elegant Ajax has to load the 80K framework of jquery.
But now, we can use fetch to provide a common definition of request and Response (and other objects related to network requests).
It also provides a definition of CORS and HTTP
The original header information is combined to replace the original definition of separation.
But,fetch compatibility, you can see, compatibility is poor, the mobile end is annihilated, but can use Fetch Polyfill
Links: https://www.jianshu.com/p/11f64a03d3f3traditional XHR requests are very confusing to write, such as:
1var xhr =NewXMLHttpRequest ();2Xhr.open (' GET ', URL);3Xhr.responsetype = ' json ';4 5Xhr.onload =function () {6 Console.log (xhr.response);7 };8 9Xhr.onerror =function () {TenConsole.log ("Oops, Error"); One }; A -Xhr.send ();
But after using fetch, such as:
1 fetch (URL). Then (function (response) {2 return Response.json (); 3 }). Then (function (data) {4 console.log (data); 5 }). Catch (function (e) {6 console.log ("Oops, Error"); 7 });
So the style of this chained call will look very comfortable.
If we use the arrow function again, it will be more concise.
1 Fetch (URL). Then (response = Response.json ())2 . Then (data = Console.log ( Data)3 . Catch(E = Console.log ("Oops, Error", E))
Basic Use Method
Fetch must accept a resource path as a parameter, and return a promise, so we can use the method of chaining calls directly.
1Fetch ("/getallproduct"). Then (function (res) {2 returnRes.json ();3 }). Then (function (data) {4 if(Data.code = = 200) {5Console.log (' Get to all products ', data.data);6 that.props.addAllProduct (data.data);7}Else {8 Console.log (data.message);9 }Ten})
This way, we can send an AJAX request.
1 /*The return data for the client is encapsulated2 * @param [code] (number) code for the returned status code3 * @param [message] (string) message is the returned information4 * @param (any) data is optional and is returned to the front end5 */6 //Note: Res in Retrunjson is the res in the callback function of node processing interface, which is required. 7 function Returnjson (res, code, message, data) {8var response = {9 Code:code,Ten Message:message One }; A if(typeof data!== ' undefined ') { -Response.data =data; - } the Res.json (response); - //After returning this request, you must res.end () to indicate the end of the request, or the background may crash. - res.end (); - } + -Router.post ('/register ', Function (req, res) { +Let UserName =Req.body.username, APassword =Req.body.password, atPasswordagain =Req.body.passwordAgain, -Type =Req.body.type; - console.log (userName, password, type); - if(Type = = 1) { - if(Password = =Passwordagain) { -Let ManagerID =uuidv1 (); in - console.log (userName, password, passwordagain); to +var newuser =NewManager ({ - Name:username, the Password:password, * Type:req.body.type, $ Managerid:manageridPanax Notoginseng }); - the manager.find (userName, function (err, user) { + if(err) { AReturnjson (res, 5001, ' Server error, registration failed '); the}Else { + if(User!==NULL) { -Returnjson (res, 4003, "This user is already registered! "); $}Else { $ //If the condition is met, the user is registered and the data is saved in the database. - Newuser.save (The function (err, user) { - if(err) { the //server-side error, failed to return status code -Returnjson (res, 500, "User registration failed!") ");Wuyi}Else { the //user data is simple, pass the user directly, if complex, we can consider using object form to pass more data. -Returnjson (res, 200, "User Registration successful! ", user); Wu } - }); About } $ } - }); -}Else { -Returnjson (res, 4001, "User two times input password inconsistent!") "); A } +}Else if(Type = = 2) { the - if(Password = =Passwordagain) { $Let userId =uuidv1 (); the the console.log (userName, password, passwordagain); the thevar newuser =NewUser ({ - Name:username, in Password:password, the Type:req.body.type, the Userid:userid About }); the the user.find (userName, function (err, User) { the if(err) { +Returnjson (res, 5001, ' Server error, registration failed '); -}Else { the if(User!==NULL) {BayiReturnjson (res, 4003, "This user is already registered! "); the}Else { the //If the condition is met, the user is registered and the data is saved in the database. - Newuser.save (The function (err, user) { - if(err) { the //server-side error, failed to return status code theReturnjson (res, 500, "User registration failed!") "); the}Else { the //user data is simple, pass the user directly, if complex, we can consider using object form to pass more data. -Returnjson (res, 200, "User Registration successful! ", user); the } the }); the }94 } the }); the}Else { theReturnjson (res, 4001, "User two times input password inconsistent!") ");98 } About } -});
This way, we can handle an AJAX request.
Note the point:
1. Fetch () returns a Promise object.
The Promise object used by fetch allows us to write asynchronous functions in a synchronous way.
2, the Fetch API can be combined with async and await to use.
Fetch is based on promise implementation, but using promise's notation, we can still see the shadow of callback, if combined with async and await to use, still very good.
3. The SPI provided by the Fetch API includes, but is not limited to, all features of the XHR.
4. The fetch API can be cross-domain.
Reference: https://fetch.spec.whatwg.org/#http-cors-protocol
Cross-domain requests must include Origin as the header.
5. Fetch provides a common definition of the request and response objects.
Fetch provides a common definition of request and Response (as well as other objects that are related to network requests) . In a fetch request, it is perfectly possible to use only request and response two objects, set parameters via request, and process the return value through response .
So, we can define a fetch as follows:
1var myheaders =NewHeaders ();2Myheaders.append (' Content-type ', ' image/jpeg ');3var option = {method: ' GET ',4 Headers:myheaders,5Mode: ' Cors ',6Cache: ' Default ' };7var myrequest =NewRequest (' Https://api.github.com/users/mzabriskie ', option);8 Fetch (myrequest). Then (function (response) {9 ... Ten});
Reference article: HTTPS://GITHUB.COM/CAMSONG/BLOG/ISSUES/2
Use of Fetchapi