ES6 Fetch API和Cookie相关的知识点

149 阅读1分钟

Jerry Wang曾经写过一篇比较web应用处于stateful和stateless不同状态下的行为差异,发表在SAP社区上:

blogs.sap.com/2017/03/31/…

结论就是stateful的BSP应用会通过串行方式依次处理传进来的请求。

看这个例子,客户端发送A和B两个请求给服务器,两个请求分别需要3秒和2秒完成。

对于stateful BSP应用来说,因为是串行处理,所以第二个请求实际上需要3+2=5秒才能从服务器端返回,这一点在Chrome开发者工具的network标签里观察得很清楚。

大家能发现上图的客户端请求发送我用的是jQuery。当我换成ES6的fetch API时,我发现一切不再工作了。

源代码如下:

<%@page language="abap" %>
<%@extension name="htmlb" prefix="htmlb" %>
<!DOCTYPE html>
<html>
<head>
<title>Jerry Test Stateful</title>
</head>
<body>
<button onclick="fire()">Fire two request</button>
<script>
function wrapperOnFetch(url){
  fetch(url).then(function(response){
    return response.json();
  }).then(function(json){
      console.log(url + ":" + json.message);
  });
}
function fire(){
  wrapperOnFetch("first.json");
  wrapperOnFetch("second.json");
}
</script>
</body>
</html>

此时,stateful BSP应用对这两个请求的处理表现得像并行处理一样。

为了找到引起jQuery和ES6 fetch API的差异原因,我比较了两种发送的HTTP请求,发现了一些差异:

通过jQuery.ajax方法发送的请求,带有Cookie:

而ES6 fetch API发送的则没有:

在fetch的官方文档里发现了一个参数:
developer.mozilla.org/en-US/docs/…
credentials: “include”.

function wrapperOnFetch(url){
 // enable session cookie sent with request
  fetch(url,{ credentials:"include" }).then(function(response){
    return response.json();
  }).then(function(json){
      console.log(url + ":" + json.message);
  });
}

带上之后,fetch API的请求也带有期望的cookie,并且之后行为完全和jquery的AJAX方法一致了:同时到达服务器的两个请求按照串行方式依次被处理。

要获取更多Jerry的原创文章,请关注公众号"汪子熙":