Here is my code. Both index.html and service-worker.js are served on http://localhost:8080.
index.html
<!doctype html>
<html lang="zh">
<head>
<script>
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/service-worker.js", {
scope: "/",
// scope: "http://localhost:9999/"
});
}
</script>
</head>
<body>
<button id="sendApiRequest">send cors-request</button>
<script>
document.querySelector("#sendApiRequest").addEventListener("click", () => {
const API = "http://localhost:9999/api/data";
fetch(API);
});
</script>
</body>
</html>
service-worker.js
self.addEventListener("fetch", (event) => {
console.log("fetch event fired", event.request.url);
});
Below is my simulated server-side API code which served on http://localhost:9999
// Mock API server with NodeJs
const http = require('http');
const server = http.createServer((req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
const data = {
msg: 'success',
time: new Date().toLocaleString(),
}
res.end(JSON.stringify(data));
});
const port = 9999;
server.listen(port, () => {
console.log(`backend api on http://localhost:${port}`);
});
When I click the send request button, the fetch event in service-worker.js is not triggered. What is the problem? And how should I intercept CORS requests in the service worker?
selfdefined?http://localhost:8080andhttp://localhost:9999. The fetch event fires and the api returns json. The problem seems specific to your test environment. And the console and network panels in developer tools should help you identify it.console.log("fetch event fired", event.request.url);the console panels in developer tools does not output log.