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

When entering a sub-URL into the browser address bar, the routes do not display as expected

I am encountering an issue with navigating to different routes within my React application. While the home route is visible and functions properly when I start the app locally (npm run dev), I am unable to access other routes. No errors are displayed in t ...

Rendering templates using AngularJS within a Play Framework 2 project

I am currently in the process of transforming my application built on Play Framework 2.5 into a single page application using AngularJs. Here is an overview of what I was previously doing: Displaying a list of posts, utilizing Scala Template's @for ...

When attempting to display a sub view in Express, a 404 error is encountered

I am currently working with express and jade to display a web page. My intention is to render the page using this format 'http://127.0.0.1:5000/services/landfreight' but I keep encountering a 404 error. router.get('/service/landfreight' ...

In Next.js, a peculiar issue arises when getServerSideProps receives a query stringified object that appears as "[Object object]"

Summary: query: { token: '[object Object]' }, params: { token: '[object Object]' } The folder structure of my pages is as follows: +---catalog | | index.tsx | | products.tsx | | | \---[slug] | index.tsx | ...

Display an AJAX div when the image is hovered over and have it track the movement of

I am seeking assistance with my website project, which involves providing users with download links to movies. However, I am struggling to make the preview_block div(id) appear when the mouse hovers over the movie_block div(id). Additionally, I am having ...

Automate the input provided to yeoman command line interface for implementing CI/CD tools

When executing Yeoman, it prompts for input one by one. Is there a way to provide all inputs at once or programmatically? For instance: yo azuresfguest It requests 5 inputs to be added, which I would like to provide in one go for running in a CI/CD syst ...

The most recent version of Angular featuring the powerful Angular-anim

Currently, I am in the process of revamping an application that was initially developed using a combination of jquery, bootstrap, and kendo ui. Moving forward, the application will transition to an angular (2/4) and kendo framework. In the previous setup, ...

Guide on Retrieving the Current URL in NodeJS

Currently, I am utilizing express in conjunction with node.js. In my setup, the following code is present: app.get('/callback', async function (req, res) { Whenever a user reaches the callback section of my website, I expect to receive the req ...

Attempting to transfer a username String from the client to the server using React and Typescript

I am working on a project where I need to send the username of a logged-in user from the Client to the Server as a string. Currently, I am able to successfully send an image file, but now I also need to send a string along with it. What I aim to do is repl ...

Exploring tailored markup features in Next.js version 13

I am trying to optimize my website for social media sharing on platforms like WhatsApp. I have been experimenting with different methods to set custom markup in Next.js 13, but haven't achieved the desired outcome yet. Your help and insight are greatl ...

Tips for applying multiple filters to JSON data with JSON_VALUE?

I am attempting to query a collection of JSON objects to retrieve data: create table test (LINE_SPECS nvarchar(max)); insert into test values (N' { "lineName":"GHjr", "pipeDiameter":"12", "pipeLength":"52000", "pressure":"15", "volume":"1 ...

What are some ways to incorporate JQuery with getElementById?

i am trying to retrieve all input elements within a form using JavaScript formEditable = document.getElementById("formid").getElementsByTagName("input"); However, I would like to achieve the same result using jQuery instead formEditable = $("#formid").f ...

Is there a way to check for invalid string literals within a string?

Looking for a way to test for invalid (unclosed) strings within a given string? This regex might help: /"[^"\\]*(?:\\[\S\s][^"\\]*)*"|'[^'\\]*(?:\\[\S\s][^'\\]* ...

JavaScript issues in FireFox and Internet Explorer when using JQuery

I have developed a PHP GD image for generating captcha images, saved as image.php. Each time it creates a unique captcha image. Inside the signup.php file: <img alt="" src="image.php"> <input type="button" id="btn" value="cannot read captcha"&g ...

How can AngularJS handle multiple routes using unique templates while sharing the same controller?

I am currently researching whether I can achieve the functionality described in the title. Here are my initial thoughts: Let's consider the following routes I have set up: .when('/', { templateUrl : 'partials/homepage.html&ap ...

Objects that are included into an array will end up with an undefined value

Currently, I am in the process of coding a command for my Discord bot that involves adding items to an array of objects stored within a JSON file. To achieve this functionality, I have implemented the following code snippet: let rawdata = fs.readFileSync(& ...

Converting JSON formats with Python module: A step-by-step guide

Is there a way to use a Python module to convert one JSON format to another? I have a JSON object and need to extract the keys and values. How can this be accomplished? Thank you in advance. Input json: { "A": { "sensitive": false, "type": " ...

Displaying data from a JSON file retrieved through AJAX within AMP

I am currently in the process of integrating an AMP-Version of a website that connects to a third-party REST endpoint. The endpoint returns JSON data, and I need to display a portion of this data on the website. I have already attempted using amp-list, bu ...

Implementing Jquery to Identify the Matching Indices of Two Arrays

I need to find the indices of similar values in array1 and array2, and then save them in a variable named stored_index. array1 = ["50","51","52","53","54","55","56","57","58","59"]; array2 = ["59","55","51"]; The desired result for stored_index is: sto ...

What are the best methods to prevent Json/Dict responses from being converted to strings when saving to a dataframe?

Running an API and storing the responses as dictionaries using response.to_dict() to create a new column for future reference. Here is an example dataframe: dict1 = {'thing': 200, 'other thing': 18, 'available_d ...