服务工作者:获取请求时检索 xhr 正文 [英] Service Workers: Retrieve xhr body when fetching the request

查看:32
本文介绍了服务工作者:获取请求时检索 xhr 正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检索我从 xhr (XMLHttpRequest) send(body) 调用发送的正文?我的 xhr 变量是一个 XMLHttpRequest,可以使用 POST 方法调用内部 url(例如:/path/api)

How can I retrieve the body I sent from a xhr (XMLHttpRequest) send(body) call?. My xhr variable is an XMLHttpRequest ready to call an internal url using the POST method (Ex: /path/api )

xhr.send("a=1");

另一方面,我实现了一个 Service Worker 并创建了处理程序来捕获所有获取请求

On the other side, I have implemented a Service Worker and created the handler to catch all fetch requests

self.addEventListener('fetch', function(event, body) 
{ 
event.respondWith( //Check content of event.request.body to run the right action );
}

我可以将 event.request 的一些属性作为 event.request.url 检索,但我无法找到检索原始 xhr 正文的方法(即a=1").

I can retrieve some properties of the event.request as event.request.url, but I am unable to find the way to retrieve my original xhr body (i.e. "a=1").

有趣的是,当 Service Worker 处理这个请求,并调用网络获取结果时,

Interestingly, when the Service Worker handles this request, and calls the network to get the result,

return fetch(event.request);

服务器可以访问正文数据.

the server get access to the body data.

下面是我在 SW fetch 方法中收到的 Request 对象的摘录

Below an extract of the Request object I receive within the SW fetch method

Request {method: "POST", url: "http://localhost/services", headers: Headers
, referrer: "http://localhost/m1/", referrerPolicy: "no-referrer-when-downgrade"…}

bodyUsed:false
credentials:"include"
headers:Headers
  __proto__:Headers
integrity:""
method:"POST"
mode:"cors"
redirect:"follow"
referrer:"http://localhost/path/"
referrerPolicy:"no-referrer-when-downgrade"
url:"http://localhost/path/api"

有关如何在 Service Worker fetch() 捕获中检索发送请求的内容/正文的任何​​建议?

Any suggestion on how to retrieve the content/body of the send request within the Service Worker fetch() capture?

谢谢!

推荐答案

这对大多数人来说可能很明显,但我想在回复中添加一些注释,以防将来有人遇到我同样的情况.

This is maybe obvious for most people, but I wanted to add some notes with the response, in case someone is in my same situation in the future.

p>

有几种方法可以从请求中检索正文,具体取决于正文的发送方式

There are several methods to retrieve the body from the request, depending on how the body has been sent

event.request.arrayBuffer()
event.request.blob()
event.request.json()
event.request.text()
event.request.formData()

这些方法中的任何一个都将返回一个 Promise,其中将包含正文内容.瞧!

Any of those methods will return a Promise, which will include the body content. Voila!

我还要感谢 Nikhil Marathe (https://hacks.mozilla.org/2015/03/this-api-is-so-fetching/) 帮助我了解这一切是如何运作的.

I need to thank also Nikhil Marathe (https://hacks.mozilla.org/2015/03/this-api-is-so-fetching/) for helping me understand how all this works.

这篇关于服务工作者:获取请求时检索 xhr 正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆