While attempting to use JavaScript and AJAX to read a JSON object, I encountered an issue caused by the CORS

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
       function fetchData(){
         var xhttp = new XMLHttpRequest();
         xhttp.onreadystatechange = function(){
          if(this.readyState == 4 && this.status == 200){

            var jsonObj = JSON.parse(xhttp.response);
            document.getElementById('result').innerHTML = jsonObj.name;
          }
         };
         xhttp.open("GET", "student.json", true); 
         xhttp.send();
       }


    </script>
    <input type="button" name="name" onclick="fetchData()" value="Click"/>
    <div id="result"></div>
</body>
</html>

I encountered an issue with the following error message: 6hp.html:21 Access to XMLHttpRequest at 'file:///C:/Users/Admin/Desktop/ind/ip-simple/student.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

Answer №1

I found success with your solution using a file setup similar to this. Consider relocating the json file to the directory of your html file.

It's possible that browsers limit access to files from scripts within the same folder, but further testing may be needed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on adjusting a JavaScript animation function

I'm currently working on adjusting the animation function within the "popup" class that controls the gallery section of a website. When the page loads, an image and background start expanding from zero scale in the center to 100 VIEWPORT HEIGHT (VH) a ...

Removing a CSS class using JQuery

Within my website layout, I have a div that is dynamically included using PHP. This div is inserted in two different locations, each inside its own parent div. <div id="parent_div"> <div id="contact_details_div" class="contact_details_div sam ...

Can a specific CSS rule be written in Material UI using makeStyles that will only apply if the element has both classes together?

It's common knowledge that achieving this in CSS is a possibility. .makeStyles-mainNavWrapper-67.sticky{ position: fixed; top: 0px; opacity: 1; transition: opacity 1s ease; padding: 10px; } I am curious to find out if this can be achieved ...

Convert an array of strings in C# into a JSON array using serialization

In my _Layout.cshtml file, I have the following code. The purpose is to populate some security items in my JavaScript code. LoggedIn and username work fine, but there seems to be an issue with how the roles are being displayed in the JavaScript. The Roles ...

`There was an issue with an unfinished string literal.`

Currently, I am utilizing jQuery to display the information from a JSON string generated by PHP and extracted from a database. However, I have encountered an issue where some of the data spans multiple lines... How can I prevent this from triggering an un ...

Tips for invoking a function from a JavaScript file within an Angular component

This particular query remains unanswered and pertains to AngularJS. I am seeking a solution specifically for Angular, as none of the existing answers online seem to be effective in my case. Here is an outline of my code: Columns.js export class Columns { ...

What is the best way to understand and interpret the decoded JSON array data?

I'm finding it challenging to interpret this JSON decoded array. It's more complex than what I usually work with, so any assistance would be greatly appreciated. Thank you in advance. array(1){ [0]=> object(stdClass)#1 (11){ ["id ...

Syntax error in node/express: missing closing parenthesis after argument list

Just starting out with Node.js... const express = require('express'); const bodyParser= require('body-parser'); const MongoClient = require('mongodb').MongoClient; const app = express(); app.use(bodyParser.urlencoded({extend ...

Disabling collapse in Bootstrap 5 is impossible using stopPropagation() when clicking on a particular element

I'm attempting to prevent an element from collapsing/expanding when clicking a checkbox inside it. In my example on codepen, my code worked fine with Bootstrap v4, but after switching to v5, the stopPropagation function doesn't seem to work. Yo ...

Single-use binding format

I am a beginner with Angular and I have some doubts about the syntax used in Angular. In AngularJS, we can achieve one-time binding like this: <p>{{::myVar}}</p> In Angular, I know we can do it differently. <p [innerText]="myVar"></ ...

Combining multiple directories into a single output using the rollup command

Alright, let's talk about my directory setup: mods/ -core/ --index.js --scripts/ ---lots of stuff imported by core/index Currently, the typical rollup process works smoothly if you want to create something like mods/core/index.min.js. However, I ha ...

The uncertainty surrounding the usage of checkboxes in D3.js

I am faced with the challenge of adding checkboxes to multiple groups within an SVG, each containing a circle and text element. I have attempted to accomplish this by using D3 to append foreignObject tags and then add checkboxes to each group. The code I h ...

Issue with Material UI components: The Select component is collapsed and the autoWidth functionality is not

The Material UI (React) Select component is not expanding in width as expected, even with the autoWidth property. https://i.sstatic.net/h3H0V.png <FormControl margin="dense"> <InputLabel id="prefix-label">Prefi ...

Obtaining JSON request body in Sinatra using Ruby

I'm working on setting up an API server that will be able to receive JSON data. I've written some code for it, but unfortunately, I've encountered a JSON::Parse error-765 when trying to run the server. I'm not sure what is causing this ...

Using Ruby on Rails to render a partial template inside a JSON object array

Struggling to include a partial in an ajax request with Ruby on Rails... Here is my array variable: @return = { :error => false, :response => "Added", :partial => ... } render :json => ActiveSupport::JSON.encode( @return ) Replace ... with ...

Is there a way to delegate properties in Angular 2+ similar to React?

When working with React, I have found it convenient to pass props down dynamically using the spread operator: function SomeComponent(props) { const {takeOutProp, ...restOfProps} = props; return <div {...restOfProps}/>; } Now, I am curious how I ...

Browsing using the "touchmove" feature feels extremely laggy

I implemented a workaround to achieve "position:fixed" on mobile devices, specifically my Android device. This involved creating two divs with heights that combined to match the screen height through JavaScript, and adding touch listeners to the bottom div ...

Embed API allows users to showcase a variety of charts all on one page

I am trying to incorporate two google analytics timeline charts using the embed API on a single page. However, I am facing an issue where only one chart is appearing. The first chart should display bounce rate data and the second chart should display sessi ...

Ways to target only the adjacent div

My goal is to target only the next div with the class name indented. Each indented div should have the same id as the <li> element right before it. Currently, I want each div with the class name indented to have the id of the previous <li>. He ...

The function URL.createObjectURL() is failing to work across all browsers

Despite my efforts, I'm feeling tired as none of the solutions seem to work for me. Here is the HTTP call in Angular that I am struggling with: $http({ method: 'GET', url: API_URL + 'v1/file/' + candidateId + '/download& ...