Fetch instead of XMLHttpRequest (Json-server analog Backend interface)

Source: Internet
Author: User
Tags send cookies

First, the fetch is the XMLHttpRequest alternative plan. To put it bluntly, it is possible to fetch the data in addition to Ajax for the background.

Second, the support of fetch is not very good. Attached to the BOM can be accessed directly by the browser.

1. Support situation

  

Of course, if fetch is not supported, you can use a third-party ployfill to implement only Fetch:whatwg-fetch

Three, json-server analog back-end interface

1. Initializing the project NPM Init

2. Installing JSON-SERVER:NPM install--save-dev Json-server

3. Create a Db.json write below the directory

{"  posts": [    {"id": 1, "title": "Json-server", "Author": "Typicode"}  ],  "comments": [    {"id": 1, "Bo Dy ":" Some comment "," PostID ": 1}  ],  " profile ": {" name ":" Typicode "}}

4. Add a piece of code to Package.json

"Scripts": {  //  new Add line  "test": "..."}

5.NPM Run Server

  

Three interfaces have been generated, supported post(新增) delete(删除) put(修改) get(查询) ;

I'm not going to say anything about json-server other configurations. Interested in their own official website to view the next. Currently only simulates a background interface.

Four, GET request.

1.

Fetch (' Http://10.63.68.93:3000/profile ', {        ' GET '    }). Then (res)={           return Res.json ()     = =        {//Object {name: "Typicode"}    })

2.get Transfer of request parameters

Take the parameters above the URL

Fetch (' http://10.63.68.93:3000/profile?a=2&b=1 ', {        ' GET '    }). Then (res)={           return Res.json ()     = =        {//Object {name: "Typicode"}    })

V. POST request

1. Similar to a GET request, the POST request is specified in the second parameter of the fetch:

Fetch (' http://10.63.68.93:3000/comments ', {        ' POST '    }). Then (res)={         return Res.json ()     = =        {//Object {name: "Typicode"}    })

Parameter passing for 2.POST requests

var paramsstring = "Q=urlutils.searchparams&topic=api"    varnew  Urlsearchparams (paramsstring);    Fetch (' http://10.63.68.93:3000/posts ', {        ' POST ',        //  Here is the request object   specific API to see the fetch official website urlsearchparams    }). Then (res)=        {return Res.json ()     = = {        console.log (res)     })

Six, set the request header

New Headers (); Myheaders.append (' content-type ', ' text/xml '); Myheaders.get (' Content-type ') ; // should return ' Text/xml '

  

varparamsstring = "Q=urlutils.searchparams&topic=api"varSearchparams =NewUrlsearchparams (paramsstring); Let Myheaders=NewHeaders (); Myheaders.append (' Content-type ', ' text/xml '); Myheaders.get (' Content-type '); /*myheaders = new Headers ({"Content-type": "Text/plain", "Content-length": content.length.toString (), "x-custom-     Header ":" Processthisimmediately ",}); */    //should return ' Text/xml 'Fetch (' http://10.63.68.93:3000/posts ', {method:' POST ', Headers:myheaders, Body:searchparams//here is the request object specific API to see the urlsearchparams of the fetch official website}). Then (res) ={        returnRes.json ()}). Then (res={Console.log (res)})

Vii. Mandatory with cookies

By default, fetch does not send or receive any cookies from the server, and if the site relies on maintaining a user session, it causes an unauthenticated request (to send cookies, the credential header must be sent).

Eight, fetch encapsulates AJAX requests

/** * Convert object to a=1&b=2 form * @param obj object*/functionObj2string (obj, arr = [], idx = 0) {   for(Let iteminchobj) {Arr[idx++] =[item, Obj[item]]}return NewUrlsearchparams (arr). toString ()}/** * Real request * @param URL Request address * @param options Request Parameter * @param method request*/functionCOMMONFETCDH (URL, options, method = ' GET ') {Const SEARCHSTR=obj2string (options) let Initobj= {}  if(method = = = ' GET ') {//if it is a GET request, the stitching URLURL + = '? ' +searchstr initobj={method:method, credentials:' Include '    }  } Else{initobj={method:method, credentials:' Include ', headers:NewHeaders ({' Accept ': ' Application/json ',        ' Content-type ': ' application/x-www-form-urlencoded '}), body:searchstr}} fetch (URL, initobj). Then (RES)= {    returnRes.json ()}). Then (RES)= {    returnres})}/** * GET request * @param URL Request address * @param options Request Parameters*/functionGET (URL, options) {returnCOMMONFETCDH (URL, options, ' GET ')}/** * POST request * @param URL Request address * @param options Request Parameters*/functionPOST (URL, options) {returnCOMMONFETCDH (URL, options, ' POST '))}

Fetch instead of XMLHttpRequest (Json-server analog Backend interface)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.