[PWA] 6. Hijacking response

本文介绍了一种在服务器端处理404错误的方法。当URL未匹配到任何API端点时,通过返回自定义的404错误页面或特定图片来处理这种情况。此外,还提供了一个简单的示例代码,用于演示如何使用JavaScript实现这一功能。

For example, if the url is not match to any API endpoint, we want to return 404 error message.

 

So first thing, we want to send the request to the server first. If got the response, then we just return it back.

self.addEventListener('fetch', (event) => {

    event.respondWith(
        fetch(event.request).then( (response) => {
              // fetch the request frist

              return response;
        })
    )
});    

 

Then we handle 404 error:

self.addEventListener('fetch', (event) => {

    event.respondWith(
        fetch(event.request).then( (response) => {
              if(response.status === 404){
                  return fetch('/img/dr-evil.gif');
              }

              return response;
        }).catch( () => {
             return new Response("Something totally wrong");
        })
    )
});                        

 

转载于:https://www.cnblogs.com/Answer1215/p/5498410.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值