PWA-网络
fetch API
Get
fetch('/some/url',{
method:'GET'
}).then(function(resp){
//success
}).catch(function(error){
//error
})
Post
fetch('/some/url',{
method:'POST',
headers:{
'auth':'1234'
},
body:JSON.stringify({
name:'demo'
})
}).then(function(resp){
//success
}).catch(function(error){
//error
})
fetch 事件
Service Worker可以拦截浏览器发出的任何Http请求,这些Http请求都将触发fetch事件,通过监听fetch事件可以实现自主控制请求及返回。例如
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(resp => {
if (resp) {
return resp;
}
var requestToCache = event.request.clone();
return fetch(requestToCache).then(
(response) => {
if (!response || response.status != 200) {
return response;
}
var responseToCache = response.clone();
caches.open(cacheName).then(cache => {
cache.put(requestToCache, responseToCache)
})
return response;
}
)
})
)
})