in JavaScript Technology

How to Use JSON Data in JavaScript with Ajax and Handle CORS Errors

When working with JSON data in a web application, integrating it into an HTML document can sometimes lead to unexpected errors. One common issue developers encounter is: Access to XMLHttpRequest has been blocked by CORS policy. This guide will explain the steps to use JSON data effectively and resolve this error. Example Scenario Here’s a basic example of retrieving JSON data using jQuery’s Ajax function. Step 1: Create a JSON File Let’s create a file called New.json with the following content:

[
    { "firstname": "Thomas", "lastname": "Anderson" },
    { "firstname": "Agent", "lastname": "Smith" },
    { "firstname": "Agent", "lastname": "Brown" }
]

Step 2: Retrieve JSON Data with Ajax
Below is a simple script to load the data when a <div> element is clicked:

<script type="application/javascript">
$(document).ready(function() {
    $("div").click(function() {
        $.ajax({
            type: 'GET',
            url: './New.json',
            dataType: 'json',
            success: function(data) {
                console.log(data);
            },
            error: function(xhr, status, error) {
                console.error("Error:", error);
            }
        });
    });
});
</script>

When this script is executed, you might encounter the following error in your browser's console:

Access to XMLHttpRequest has been blocked by CORS policy.

Why Does This Error Occur?

CORS (Cross-Origin Resource Sharing) is a security feature implemented in browsers to restrict cross-origin HTTP requests. This error happens because:

  • The server hosting the New.json file does not allow requests from the domain running your script.
  • The file is being accessed using file:// protocol instead of a web server (e.g., http://localhost).

Solutions to Fix the CORS Error

1. Serve Your JSON File from a Local or Remote Web Server

Instead of opening your HTML file directly in a browser, use a local server like:

  • Node.js with Express
  • Python HTTP Server:
python -m http.server 8000
  • Live Server (a VS Code extension)

This ensures the browser properly recognizes requests as HTTP/HTTPS.

2. Configure CORS on the Server

If you own the server hosting New.json, add CORS headers to allow requests. For example:

  • On an Express.js server:
const cors = require('cors');
app.use(cors());
  • On an Apache server, add this to .htaccess:
Header add Access-Control-Allow-Origin "*"

3. Use a Proxy Server

If you can’t modify the server, use a proxy to fetch the data. Proxy servers bypass CORS by making the request on your behalf.

Example:

const proxyUrl = "https://cors-anywhere.herokuapp.com/";
const url = proxyUrl + "https://example.com/New.json";

4. Test Your Array’s Format

Ensure your JSON is properly formatted. JSON objects must be enclosed in {} while arrays should be inside [].


Additional Debugging Tips

  1. Always inspect the browser console for detailed error messages.
  2. Use tools like Postman or fetch API to test API endpoints.
  3. Read the official CORS guide for more information: MDN CORS Documentation.

With these steps, you should be able to use JSON data effectively in your project and resolve any CORS-related issues.

If you’re still facing problems, feel free to comment below or refer to the Cross-domain Ajax with CORS guide for advanced solutions.