JS--Fetch API

2019-04-29  本文已影响0人  小懒豆

fetch()

使用 Fetch

Headers()

var myHeaders = new Headers(init);
myHeaders.append('Content-Type', 'image/jpeg');
myHeaders.get('Content-Type'); // Returns 'image/jpeg'
var secondHeadersObj = new Headers(myHeaders);
secondHeadersObj.get('Content-Type'); // Would return 'image/jpeg' — it inherits it from the first headers object
//------------------------------------------------------------
myHeaders.append('Content-Type', 'text/xml');
myHeaders.append('Vary', 'Accept-Language');

// Display the key/value pairs
for (var pair of myHeaders.entries()) {
   console.log(pair[0]+ ': '+ pair[1]);
}
//content-type: text/xml
//vary: Accept-Language

Request()

const myRequest = new Request('http://localhost/api', {method: 'POST', body: '{"foo":"bar"}'});
 
const myURL = myRequest.url; // http://localhost/api
const myMethod = myRequest.method; // POST
const myCred = myRequest.credentials; // omit
const bodyUsed = myRequest.bodyUsed; // true
fetch(myRequest)
  .then(response => {
    if (response.status === 200) {
      return response.json();
    } else {
      throw new Error('Something went wrong on api server!');
    }
  })
  .then(response => {
    console.debug(response);
    // ...
  }).catch(error => {
    console.error(error);
  }); 

Response()

var myResponse = new Response();
上一篇下一篇

猜你喜欢

热点阅读