xmlhttprequest - 服务人员 : Retrieve xhr body when fetching the request

标签 xmlhttprequest fetch send service-worker

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

xhr.send("a=1");

另一方面,我实现了一个 Service Worker 并创建了处理程序来捕获所有获取请求
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”)。

有趣的是,当 Service Worker 处理这个请求,并调用网络获取结果时,
return fetch(event.request);

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

下面是我在 SW fetch 方法中收到的 Request 对象的摘录
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() 捕获中检索发送请求的内容/正文的任何​​建议?

谢谢!

最佳答案

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

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

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

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

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

关于xmlhttprequest - 服务人员 : Retrieve xhr body when fetching the request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39649626/

相关文章:

php - MYSQL 缺少第一行数据

javascript - value Ajax 文件 uploader +406 Not Acceptable Firbug 中的错误

javascript - ajax XHR加载失败: POST

java - Spring 数据JPA : findAll with Specification and Pageable fails on count query

javascript - HTTP Promise - 处理错误

android - Intent Action SEND 总是打开 GMail

http - 自定义请求 header 要遵循的标准

javascript - 确保类构造函数中的异步代码在调用类方法之前完成

html - 空表单 POST 数据

java - "send immediately"的单字命名约定