如何在Service Worker的fetch方法中获取JS POST请求携带的参数
你可以通过读取Request对象的body流获取jQuery.ajax()传入的data参数,操作时注意需要先克隆请求对象,避免body流被消费后导致原请求无法正常发起或缓存。
具体实现逻辑
- Request对象的body是只读流,只能读取一次,因此必须调用
.clone()方法克隆一份再读取body内容 - 针对你提交的表单格式
data,可以通过.text()方法直接拿到序列化的参数字符串,要是你传的是JSON格式数据,替换为.json()方法即可 - 额外提示:默认Cache API不支持POST请求作为缓存键,如果你需要缓存POST响应,建议将「请求URL + 请求参数哈希值」作为自定义键,存入IndexedDB或者构造自定义GET格式的缓存键使用Cache API存储。
修改后可直接运行的代码
self.addEventListener('fetch', function(event) { const requestUrl = new URL(event.request.url); // 提前判断是否为POST请求,克隆后读取data let postData = null; if (event.request.method === 'POST') { // 克隆请求,避免消费原请求的body流 event.request.clone().text().then(data => { postData = data; // 这里就拿到了你要的data参数,可自行判断是否符合缓存规则 console.log('拿到的POST请求参数:', postData); }).catch(err => { console.log('读取POST参数失败:', err); }) } event.respondWith( caches.match(event.request) .then(function(response) { if(response) { console.log('return cache '+requestUrl.href); return response; } console.log('return classic + save'); return fetch(event.request).then(function(response) { if(!response || response.status === undefined || response.status !== 200 || response.type !== 'basic') { return response; } var respToCache = response.clone(); caches.open('thiscache').then(function(cache) { console.log('cache opened, saving...'); cache.put(event.request, respToCache) .then() .catch(function(error) { console.log('catcherror: '+error); if(event.request.method == 'POST') { // 此处可以直接用前面拿到的postData变量 console.log('当前POST请求参数:', postData); } }) }) .catch(function(error) { console.log('Error ! '+error); }) return response; }) }) ); });
内容的提问来源于stack exchange,提问作者Vae
相关产品推荐
相关产品推荐

