简体   繁体   English

POST 请求获取正文的服务工作者获取事件

[英]Service worker fetch event for POST request get body

How can I capture the body of POST request in a Service Worker.如何在 Service Worker 中捕获 POST 请求的主体。 I am sending authentication parameters in the POST request, so I want to intercept the fetch request in service worker and show results from IndexDB.我在 POST 请求中发送身份验证参数,所以我想拦截服务工作者中的获取请求并显示来自 IndexDB 的结果。 Following is the code from my service worker以下是我的服务人员的代码

self.addEventListener("fetch", event => {
let cloned = event.request.clone();
console.log(cloned.json()); //<<- This line returns error : TypeError: Failed to execute 'json' on 'Request': body stream is locked
let response =  new Promise((resolve)=>{
  let key='mykey'; //Genereate from body, so read body
  let stored = localforage.getItem(key);
  if(stored){
      resolve(stored);
  }else{
    resolve(fetch(cloned).then(res => res.json()).then(res=>{
         localforage.setItem(key,res);
    }));    
  }
})

event.respondWith(response);

})

ps: please ignore syntax errors if any. ps:如有语法错误,请忽略。

Since request body is ReadableStream, for the reasons @Mr.Vibe mentions in the above comment it cannot be accesed through event.request.body , One way to access the body is by using await event.request.json() , However one should notice that once the request body is read it cannot be reused as body of a request as it throws an error like This ReadableStream is disturbed (has already been read from), and cannot be used as a body .由于请求正文是 ReadableStream,由于@Mr.Vibe 在上述评论中提到的原因,它不能通过event.request.body访问,访问正文的一种方法是使用await event.request.json() ,但是应该请注意,一旦请求正文被读取,它就不能被重用作为请求的正文,因为它会抛出一个错误,例如This ReadableStream is disturbed (has already been read from), and cannot be used as a body So its better we clone the request and then access its body as in await event.request.clone().json() , So that later on we could use the original request unharmed.所以最好我们克隆请求,然后像在await event.request.clone().json()中那样访问它的主体,这样以后我们就可以安全地使用原始请求。

self.addEventListener("fetch", async (event) => {
 let clonedBody = await event.request.clone().json();
  ...
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM