AngularJS's $http.get function has the ability to read text files, but it struggles with reading JSON

I'm new to angularjs and I am struggling to retrieve data from a json file using the $http.get method. It seems to work fine when I try to read a simple txt file, but not with the json file.

I can't seem to pinpoint where the issue lies...

Below is the code snippet I am working with:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Plunkr.aspx.cs" Inherits="AngularJS.Plunkr" %>

<!DOCTYPE html>
<html data-ng-app="myApp">

  <head>
      <title>content</title>
    <script src="jquery-1.8.2.js"></script>
    <script src="angular.min.js"></script>
      <script type="text/javascript">

          angular.module('myApp', [])
            .controller('myController', function ($scope, $http) {
                $scope.json = 'Cities not yet loaded.';
                $http.get('read.txt') // This works fine
                  .then(function (data) {
                      debugger;
                      $scope.json = data.data;
                  }, function (error) {
                      debugger;
                      alert('error');
                  });
            })
          ;
    </script>
  </head>

  <body data-ng-controller="myController">
    <p>JSON content should display below:</p>
    <pre>{{json}}</pre>
  </body>

</html>

The read.txt file contains only the text "Hello world".

When attempting to read the json file, the error function in the then() block is triggered.

After inspection, the error variable displayed a status of 404 and statusText as Not Found.

Here is the contents of the json file cities.json:

{
  "cities": [
    {   
        "city": "Pune", 
        "latitude": "1", 
        "longitude": "2",
        "id": "pun"
    }, 
    {
        "city": "Mumbai", 
        "latitude": "45", 
        "longitude": "23",
        "id": "mum"
    },
    {
        "city": "Delhi", 
        "latitude": "22", 
        "longitude": "676",
        "id": "del"
    },
    {
        "city": "Chennai", 
        "latitude": "45", 
        "longitude": "787",
        "id": "chn"
    }
  ]
}

I am using Visual Studio as my IDE.

I came across this example here, and it seems to run without issues on that platform.

Answer №1

The code executed without any issues and produces the desired output. Check out a live demo on this link.

If you are still facing any challenges, kindly provide more details about your issue along with the updated code.

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

A straightforward method for injecting a JSON string into a JSON field in PostgreSQL utilizing the npgsql driver

I am having issues inserting a JSON string into a JSON field in PostgreSQL using npgsql in C#. The problem I am encountering is an error message stating: column "column1" is of type json but expression is of type text Prior to attempting the insertio ...

What are the best strategies to guard against JsonConvert Deserialize object errors in cases where an object class property receives unexpected data?

When converting Json data responses into C# classes using http://json2csharp.com, I have encountered a common issue. If certain parts of the Json are missing when generating the classes, it can lead to an incomplete set of class properties, resulting in un ...

Guide to automatically loading a default child route in Angular 1.5 using ui-router

Hello, I am looking to set a default child route to load as soon as the page loads. Below is the code snippet: $stateProvider.state('userlist', { url: '/users', component: 'users', data:{"name":"abhi"}, resolv ...

Is it a mistake? Using React and ES6 without Babel may not be the

Have you ever considered bundling all of your classes into a single file without using Babel to polyfill it to ES5? If the browser doesn't support ES6, you could then use Babel in the browser or load the polyfilled bundle and manually add the dependen ...

Exploring through a dynamically generated table containing JSON data

I have successfully implemented a dynamic HTML table that is populated with JSON data based on the value of a variable when the "go" button is clicked. The initial population and search functionality work flawlessly. However, I encountered an issue when ch ...

Appending a new element to a JSON object using JavaScript

Hey there, I have a JSON object called departments. When I use console.log(departments) it displays the following data: { _id: 58089a9c86337d1894ae1834, departmentName: 'Software Engineering', clientId: '57ff553e94542e1c2fd41d26', ...

Create a series of canvas lines connecting all divs that share a common class identifier

Currently, I am in the process of creating a document that will establish a tree-type graph based on user input. My goal is to link styled divs with canvas lines to show their connection to the parent div. I have been utilizing .getBoundingClientRect() to ...

The functionality of changing the category in the second carousel slider on click using JavaScript appears to

Creating a bootstrap carousel slider that dynamically changes based on the selected category. For example, clicking on the hammer category will display only hammer images, while selecting the compass category will show compass images. Everything worked sm ...

Challenges with compiling Next.js with Tailwindcss and Sass

I recently created a simple template using Tailwind for my Next.js project. Normally, I rely on Tailwind's @layer components to incorporate custom CSS styles. However, this time I wanted to experiment with Sass, so I converted my globals.css file to ...

Saving Array into JSON Format

Currently, I am in the midst of a research project that involves storing a significant amount of external data. My chosen format for storage is JSON, which is new territory for me. The main requirement is to store a large array of data; however, all JSON e ...

How can I incorporate JSON data returned by ng-flow.js into HTML or a controller?

I've implemented ng-flow using the script ng-flow-standalone.js, which can be found here. My objective is to display only the upload field when a user adds a new item. After the photo is uploaded, additional form fields like Title and Description sho ...

Assigning an identification number to specify the type of Chip

I am currently working on a project involving Material UI "Chips" that contain text and serve as references. Within the context of my project, I have Chips for both White Advantages and Black Advantages sections. However, there are instances where these Ch ...

What is the correct way to align text in jsPDF?

I'm currently encountering an issue with the jsPDF library. Although PDF generation works fine, I am struggling to justify text properly. The align: 'justify' attribute seems to function the same as align: 'left', and setting a spe ...

The variable "artikel" is not defined in the view template located at C:xampphtdocsuts esourcesviewslayoutshome.blade.php

A variable named "artikel" is not defined (0) (View: C:\xampp\htdocs\uts\resources\views\layouts\home.blade.php) @if($artikel) @foreach($artikel as $d) <h3> {{ $d->judul }}</h3> <h3> {{ $d->penuli ...

I intend to extract the long_name value from the JSON data using AngularJS

I have been attempting to retrieve the long_name from the JSON data below using angular js, but unfortunately I am unable to successfully fetch it. CODE: { "results" : [ { "address_components" : [ { "long_name ...

How can I use regular expressions to locate a React JSX element that contains a specific attribute?

Currently conducting an audit within a vast codebase, my task involves searching for all instances of a component where it is utilized with a specific prop. I believe that using regex could prove beneficial in this situation; however, the challenge lies in ...

There seems to be an issue with the location.href function in the server-side code of

I'm encountering an issue in the code below where I am attempting to redirect to the login page, but it seems to not be functioning as expected. app.get('/current-pass', (req, res) => { res.sendFile(path.join(staticPath, "currentPass ...

Encountered an error "Not Found" when attempting to establish an AJAX connection between Javascript and Rails

I'm having an issue with a simple Rails controller method. When I call it from JavaScript as an AJAX method, I get the error message "Not Found" in the JavaScript error log, even though the method works fine when accessed directly in the browser. What ...

The lambda expression cannot be used with the operator '.'

I am attempting to craft a Linq lambda expression that will retrieve customers whose first or last names begin with specific letters. However, I am encountering an issue with the .select method where it is returning the error: The operator '.' c ...

Issue: Unable to assign headers once they have already been sent to the client

As a newcomer to the world of Node.js, I am facing some challenges. Currently, my setup includes Node.js 4.10 and Express 2.4.3. Whenever I attempt to access , I get redirected to . This redirection triggers the following error: Error: Headers cannot b ...