JS Fetch

Fetch()提供了一种方式进行跨网络异步请求资源的方式,用于访问和操作HTTP管道的部分,比如:请求和相应。

Fetch 优点主要有:

  • 语法简洁,更加语义化

  • 基于标准 Promise 实现,支持 async/await

  • 同构方便,使用 isomorphic-fetch

接收到表示错误的HTTP状态码时,fetch()返回的Promise不会被标记为reject(即使状态码为404或500)。fetch()会将Promise状态标记为resolve(但resolve返回值但OK 属性设置为 false)。网络故障或请求被阻止才会标记为reject

fetch()不会从服务端发送或接收任何cookies。发送cookies 需要设置 fetch(url, {credentials: 'include'}) 选项。

fetch请求

fetch(url).then(function(response) {

  return response.json();

}).then(function(data) {

  console.log(data);

}).catch(function(e) {

  console.log("Oops, error");

});

fetch参数

fetch()接受第二个可选参数,控制不同配置的init参数。

上传JSON数据

var url = 'https://example.com/profile';

var data = {username: 'example'};

fetch(url, {

  method: 'POST', // or 'PUT'

  body: JSON.stringify(data), // data can be `string` or {object}!

  headers: new Headers({

    'Content-Type': 'application/json'

  })

}).then(res => res.json())

.catch(error => console.error('Error:', error))

.then(response => console.log('Success:', response));

Headers

使用Headers 的接口,你可以通过Headers() 构造函数来创建一个你自己的 headers 对象。一个 headers 对象是一个简单的多名值对:

var content = "Hello World";
var myHeaders = new Headers();
myHeaders.append("Content-Type", "text/plain");
myHeaders.append("Content-Length", content.length.toString());
myHeaders.append("X-Custom-Header", "ProcessThisImmediately");
原文地址:https://www.cnblogs.com/HeavyMetalChao/p/10170872.html