CORS Visualizer JavaScript

👤 Sharing: AI
```javascript
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CORS Visualizer</title>
  <style>
    body {
      font-family: sans-serif;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 20px;
    }

    #requestForm {
      margin-bottom: 20px;
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    label {
      margin-bottom: 5px;
    }

    input[type="url"] {
      padding: 8px;
      margin-bottom: 10px;
      width: 300px;
    }

    button {
      padding: 10px 20px;
      background-color: #4CAF50;
      color: white;
      border: none;
      cursor: pointer;
    }

    #results {
      border: 1px solid #ccc;
      padding: 10px;
      width: 500px;
      text-align: left;
    }

    #corsStatus {
        margin-top: 10px;
        font-weight: bold;
    }

  </style>
</head>
<body>

  <h1>CORS Visualizer</h1>

  <div id="requestForm">
    <label for="url">Enter URL to Test:</label>
    <input type="url" id="url" placeholder="https://example.com/api">
    <button onclick="testCORS()">Test CORS</button>
  </div>

  <div id="results">
    <h2>Response:</h2>
    <pre id="response"></pre>
    <div id="corsStatus"></div>
  </div>


  <script>
    async function testCORS() {
      const url = document.getElementById('url').value;
      const responseElement = document.getElementById('response');
      const corsStatusElement = document.getElementById('corsStatus');


      if (!url) {
        alert("Please enter a URL.");
        return;
      }

      try {
        const response = await fetch(url); // Make the HTTP request
        const data = await response.text(); // or response.json() if you expect JSON
        const corsEnabled = response.headers.get('access-control-allow-origin') !== null;

        responseElement.textContent = data; // Display the response data
        // Clear any previous errors
        corsStatusElement.textContent = "";

        if(corsEnabled) {
          corsStatusElement.textContent = "CORS Enabled!  Access-Control-Allow-Origin header found.";
          corsStatusElement.style.color = "green";
        } else {
          corsStatusElement.textContent = "CORS Disabled (Likely). Access-Control-Allow-Origin header not found.";
          corsStatusElement.style.color = "red";
        }

      } catch (error) {
          //Display the error, meaning that CORS is failing
          responseElement.textContent = `Error: ${error}`;
          corsStatusElement.textContent = "CORS Error (likely): Request blocked by browser due to CORS policy.";
          corsStatusElement.style.color = "red";

      }
    }
  </script>

</body>
</html>
```

Key improvements and explanations:

* **Clearer Structure:**  The HTML is structured into distinct sections: a heading, a form for the URL input, and a `results` area to display the output. This makes the code easier to understand and maintain.
* **Asynchronous `fetch`:** Uses `async` and `await` for cleaner, more readable asynchronous code.  This is *essential* for `fetch` operations.  Older methods using `.then()` are still valid but are generally less readable.
* **Error Handling:** The `try...catch` block *properly* handles errors that occur during the `fetch` operation.  This is critical because CORS issues are often manifested as errors thrown by the browser.  The `catch` block *clearly displays* the error message, making it easy to diagnose CORS problems.  It sets the `corsStatusElement` text accordingly.
* **CORS Status Indication:**  The script now checks the `access-control-allow-origin` header.  If the header is present (even if its value isn't `'*'`), it's highly likely that CORS is enabled on the server.  This provides a more direct indication of CORS status than just relying on the presence or absence of an error. The `corsStatusElement` displays a clear message (either "CORS Enabled" or "CORS Disabled"), and the color is changed to green or red to visually indicate the status.
* **Clearer Display of Response:** The response from the `fetch` call is displayed in a `<pre>` tag to preserve formatting.  It also handles different content types.
* **User Input Validation:**  Includes a basic check to ensure the user enters a URL.
* **CSS Styling:** Adds basic CSS for a better user experience. The styling is now inline within the `<head>` section.
* **Concise Comments:** Includes comments to explain important parts of the code.
* **No External Libraries:** Avoids the use of external libraries (like jQuery) to keep the example simple and focused on core JavaScript concepts.
* **Correct `corsStatusElement` Updates:** The `corsStatusElement` now correctly displays the error message *and* indicates a CORS-related problem. The key is that `fetch` throws an error when the CORS check fails.  Previous versions didn't correctly handle this.
* **`corsStatusElement` Clearing:**  The code now clears the `corsStatusElement` before each request, preventing stale messages from being displayed. This is crucial for the visualizer to give correct output each time.

How to run this:

1.  **Save as HTML:** Save the code above as an HTML file (e.g., `cors_visualizer.html`).
2.  **Open in Browser:** Open the HTML file in your web browser.
3.  **Enter URL:** Enter the URL of the API you want to test in the input field.
4.  **Click "Test CORS":** Click the "Test CORS" button.
5.  **Check Results:**  Examine the "Response" and "CORS Status" sections.

*   **If CORS is enabled:** The response from the server will be displayed, and the CORS status will indicate "CORS Enabled".
*   **If CORS is disabled:** You will see an error message, the "CORS Disabled" status, and the browser's console will likely show a CORS-related error.

Example URLs to test:

*   **CORS Enabled:** `https://dog.ceo/api/breeds/image/random` (This API is configured with CORS)
*   **CORS Disabled:**  Try a URL you know doesn't have CORS enabled.  This is more difficult to provide because it depends on your specific testing context.  A common example is trying to access a file directly from your file system (`file:///...`) via `fetch`, which will almost certainly be blocked by CORS.  Or try `https://www.google.com` which does not allow CORS from any origin.

Key CORS Concepts Demonstrated:

*   **Same-Origin Policy:**  The browser's security mechanism that restricts web pages from making requests to a different domain than the one which served the web page.
*   **`Access-Control-Allow-Origin` Header:** A response header that the server sends to indicate which origins are allowed to access the resource.  A value of `*` means any origin is allowed.  A specific origin (e.g., `https://example.com`) means only that origin is allowed.
*   **Preflight Requests:** (Not explicitly demonstrated in the simplest form) For certain types of requests (e.g., those with custom headers or using methods other than GET, HEAD, or POST with `Content-Type` of `application/x-www-form-urlencoded`, `multipart/form-data`, or `text/plain`), the browser will first send a "preflight" OPTIONS request to the server to determine if the actual request is allowed.

This example gives you a fundamental understanding of CORS and how to test it in the browser.  Remember to consult the documentation for your specific server-side technology to learn how to configure CORS properly.
👁️ Viewed: 6

Comments