Problem saving data 2 times in 1 request
# workers-help
l
When I send a request 1 time to an index.html file that says hello world, the data KV is recorded 2 times, how can I solve this problem?
Copy code
javascript
async function handleRequest(request) {
  // Get the IP address of the incoming user from the request headers
  const ip = request.headers.get("CF-Connecting-IP");
  
  // Generate a 3-digit key
  const key = Math.random().toString().slice(2, 5);
  
  // Save the data to the KV namespace using the generated key
  await LOG_IP.put(`${ip}<${key}`, 8);
  
  // Return the original request
  return fetch(request);
}

addEventListener("fetch", (event) => {
  event.respondWith(handleRequest(event.request));
});

https://cdn.discordapp.com/attachments/1111010354877694032/1111010355175510036/Screenshot_1.png

c
it's probably because your browser is doing at least 2 requests, even if the page has no other resources, it's getting the raw html & favicon.ico (automatic)
The worker is ran for every request to every resource, unless you made the route just
/
and not
/*
(and not using a custom domain)
l
Thank you for your answer @Chaika 🙏 if I do not use /* it will not work in other url paths how can I prevent this
c
well just to exclude favicon requests, you could do something like
Copy code
js
export default {
  async fetch(request, env, ctx) {
    if (request.url.endsWith('/favicon.ico') == false) {
      // Get the IP address of the incoming user from the request headers
      const ip = request.headers.get("CF-Connecting-IP");

      // Generate a 3-digit key
      const key = Math.random().toString().slice(2, 5);

      // Save the data to the KV namespace using the generated key
      await env.LOG_IP.put(`${ip}<${key}`, 8);
    }
    // Return the original request
    return fetch(request);
  },
};
(rewritten to module format, don't use service worker format, it's ugly and slower)
if you only want one log per user per session, you could send back set a cookie and check it
l
I just want the ip address to be recorded as many requests as the user sends.
c
well your browser automatically making a request to favicon.ico is a "request the user made"
l
I understand you... I do not want to record the request from other automatically running services such as png, ico, php that the website runs
For example, In xenforo forum software, many files are running in one request
It is really a pity that when a user sends a request, it is saved in the KV storage many times
one last question
do not want to include favicon.ico and style.css
is this usage correct
c
looks ok to me
hmm being in a proxy position is a bit special, you could try something somewhat primitive like checking for the returned content-type being text/html, or maybe the referrer headers.
l
thank you I'll try that mate ❤️