Fetch and XMLHttpRequest

Source: Internet
Author: User
Tags send cookies

In addition to XMLHttpRequest objects to get data in the background, you can use a more optimal solution fetch.

Fetch has not been very supportive so far, but it has been supported in Google Chrome. Fetch hangs in the BOM and can be used directly in Google Chrome.

Check fetch support Status: Fetch support

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

Let's write the first fetch to get back-end data examples:

// 通过fetch获取百度的错误提示页面fetch(‘https://www.baidu.com/search/error.html‘) // 返回一个Promise对象  .then((res)=>{ return res.text() // res.text()是一个Promise对象 }) .then((res)=>{ console.log(res) 
Get Baidu's error page fetch via FETCH (' https://www.baidu.com/rec?platform=wise&ms=1&rset=rcmd&word=123&qid=11327900426705455986& rq=123&from=844b&baiduid=a1d0b88941b30028c375c79ce5ac2e5e%3afg%3d1&tn=&clientwidth=375&t=  1506826017369&r=8255 ', {Write the arguments passed in the URL method: ' GET ', headers: new headers ({ ' Accept ': ' Application/json ' //specified by the header, The data type obtained is JSON}).Then (res) =>{ return Res.json () //Returns a promise that can be parsed into JSON}). Then (  RES) =>{ console.log (res) //Get JSON data})
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).

// 通过fetch获取百度的错误提示页面fetch(‘https://www.baidu.com/search/error.html‘, {    method: ‘GET‘,    credentials: ‘include‘ // 强制加入凭据头 }) .then((res)=>{ return res.text() }) .then((res)=>{ console.log(res) })

Fetch and XMLHttpRequest

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.