Home >Web Front-end >JS Tutorial >Logging System with Proxy and Fetch
Proxy Object: The fetchLogger wraps the fetch function.
It uses the apply trap to intercept calls to fetch.
Request Logging:Logs the url and options of the request.
Response Handling: Logs the response status, status text, and URL.
Clones the response to ensure the body can be read multiple times.
Error Handling: Captures and logs any errors encountered during the fetch.
Using the Proxy: You can replace fetch globally by assigning the proxy to window.fetch.
// Create a logging wrapper for fetch using Proxy const fetchLogger = new Proxy(fetch, { apply: (target, thisArg, args) => { // Log the request details const [url, options] = args; console.log("Fetch Request:"); console.log("URL:", url); console.log("Options:", options); // Call the original fetch function return Reflect.apply(target, thisArg, args) .then(response => { // Log response details console.log("Fetch Response:"); console.log("Status:", response.status); console.log("Status Text:", response.statusText); console.log("URL:", response.url); // Return the response for further use return response.clone(); // Clone to allow response reuse }) .catch(error => { // Log errors console.error("Fetch Error:", error); throw error; // Rethrow the error for caller handling }); } }); // Example usage of the logging fetch fetchLogger("https://jsonplaceholder.typicode.com/posts", { method: "GET", headers: { "Content-Type": "application/json" } }) .then(response => response.json()) .then(data => console.log("Data:", data)) .catch(error => console.error("Error in fetch:", error));
window.fetch = fetchLogger;
The above is the detailed content of Logging System with Proxy and Fetch. For more information, please follow other related articles on the PHP Chinese website!