【发布时间】:2021-03-23 09:29:19
【问题描述】:
我创建了一个服务工作者来充当特定 url 的代理。 并希望从我的服务人员那里为该 url 提供所有请求。
例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
(async()=>{
try{
if("serviceWorker" in navigator){
const reg = await navigator.serviceWorker.register("./sw.js",{scope: "./my"});
console.log("Service worker registered");
}
}catch(e){
console.error("Service worker failed to register");
console.error(e);
}
})()
</script>
</body>
</html>
还有 sw.js
self.addEventListener("install",(e)=>{
console.log("my sw installed");
})
self.addEventListener("fetch",(e)=>{
const url = new URL(e.request.url).pathname;
console.log(url);
if(url === "/my/hello"){
e.respondWith(new Response("hello world",{status: 200}));
}else{
e.respondWith(new Response("Hi there, page not found",{status: 200}));
}
})
当我们在某些服务器的帮助下在浏览器中运行此代码时。
如果我在浏览器 url 中输入 http://127.0.0.1:8000/my/hello,它会给我 hello world。
现在返回http://127.0.0.1:8000/ 并从脚本或浏览器控制台发出获取请求。
(async()=>{
const res = await fetch("/my/hello");
console.log(await res.text())
})()
我收到not found。
fetch api 会直接调用 server 并绕过 service worker 吗?
【问题讨论】: