如何在服务工作者中接收请求有效载荷?

我已经使用Service Worker来拦截对安全资源的HTTP请求,并向该请求添加授权标头(如果用户已经登录)。现在,我有一个场景,服务工作人员拦截POST请求以注入授权标头。但是,服务工作者未在请求有效负载中接收数据,因此没有请求有效负载(请参见屏幕截图2)。结果,nodejs中的后端验证逻辑失败,因为没有收到有效载荷数据。理想情况下,除了授权标头之外,后端代码还应该接收有效载荷数据以保留在DB中。有指导吗?

下面的第一个屏幕截图是带有有效负载的原始请求。第二个服务工作人员没有任何请求有效负载。

这是我的服务人员代码,用于拦截提取请求:

self.addEventListener('fetch',(event) => {
  const fetchEvent = event;
  const requestProcessor = (idToken) => {
    console.log('idToken in fetch '+idToken);
    let req = event.request;
    // For same origin https requests,append idToken to header.
    if (self.location.origin == getOriginFromUrl(event.request.url) &&
        (self.location.protocol == 'https:' ||
         self.location.hostname == 'localhost') &&
        idToken) {
      // Clone headers as request headers are immutable.
      const headers = new Headers();
      for (let entry of req.headers.entries()) {
        headers.append(entry[0],entry[1]);
      }
      // Add ID token to header. We can't add to Authentication header as it
      // will break HTTP basic authentication.
      headers.append('Authorization','Bearer ' + idToken);
      try {
        req = new Request(req.url,{
          method: req.method,headers: headers,mode: 'same-origin',credentials: req.credentials,cache: req.cache,redirect: req.redirect,referrer: req.referrer,body: req.body,bodyUsed: req.bodyUsed,context: req.context
        });
      } catch (e) {
        console.error('failed to prepare new header '+ e);
        // This will fail for CORS requests. We just continue with the
        // fetch caching logic below and do not pass the ID token.
      }
    }

    return fetch(req);

  };
  // Try to fetch the resource first after checking for the ID token.
// getIdToken() returns valid idtoken for logged in user.
  event.respondWith(getIdToken().then(requestProcessor,requestProcessor));
});

  • 如何在服务工作者中接收请求有效载荷?

如何在服务工作者中接收请求有效载荷?

此致 桑托什

H42801 回答:如何在服务工作者中接收请求有效载荷?

我竭尽全力解决问题 我用以下代码找到了解决方案

async function handle(request) {
let newUrl = new URL(request.url)
return await fetch(newUrl,{
    ...request,headers: { 'Authorization': 'Bearer ' + access_token }
  }); 
}

self.addEventListener('fetch',function (event) {
    event.respondWith(handle(event.request)) 
}

浏览器网络标签是多个请求,其中一个请求进入服务器。

,

这实际上非常简单,假设有效负载是请求的主体。获取/访问它的具体方式取决于请求正文的内容类型:

event.request.arrayBuffer() // for content-type of arrayBuffer
event.request.blob()        // for content-type of blob
event.request.json()        // for content-type of json
event.request.text()        // for content-type of text
event.request.formData()    // for content-type of formData

每个人都会兑现承诺。

这笔款项记入https://stackoverflow.com/a/39653321/1971662

本文链接:https://www.f2er.com/2936503.html

大家都在问