3

I'm making a weather application where I need to grab a local JSON file from within my controller and then do stuff with the data. However, I can't get a local $http.get request to work for some reason. What should I do?

This is my current code:

var weatherApp = angular.module('weatherApp', []); 

weatherApp.controller('weatherCtrl', function ($scope, $http) {
    $scope.cities = [],
    $scope.getCities = (function() {
        $http.get('http://localhost:81/Webb/angular projekt/jsons/cities.json')
             .success(function(data, status, headers, config) {

                 console.log(data);
             })
             .error(function(data, status, headers, config) {
                 console.log(status);
             });
    }())
}

Which gives me this error:

SyntaxError: Unexpected token {                                         angular.js:11598
at Object.parse (native)
at oc (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:14:156)
at Yb (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:77:190)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:78:50
at s (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:7:302)
at Yc (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:78:32)
at c (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:79:165)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:112:343
at l.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:126:193)
at l.$digest (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:123:286)

I also tried using jsons/cities.json but that throws this error:

Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https, chrome-extension-resource.

Making a get request to an external resource works fine, but whenever I do it locally things just doesn't seem to work.

The JSON file I'm trying to get looks like this:

{"cities": {

    {   
        city: "Stockholm", 
        latitud: "59", 
        longitud: "18",
        id: "sthlm"
    }, 
    {
        city: "Göteborg", 
        latitud: "58", 
        longitud: "12",
        id: "gbg"
    },
    {
        city: "Malmö", 
        latitud: "55", 
        longitud: "13",
        id: "malmo"
    },
    {
        city: "Umeå", 
        latitud: "63", 
        longitud: "20",
        id: "umea"
    }
}
}
9
  • 1
    you aren't passing a valid URI. you can't have spaces in the URI. Commented Jan 22, 2015 at 12:31
  • 2
    The JSON is malformed too - the keys for each object need to be string escaped, and the cities should be an array. Commented Jan 22, 2015 at 12:32
  • @AndrewCounts I get the same result without. Commented Jan 22, 2015 at 12:32
  • 1
    @AndrewCounts turns out you can have a space in it, it was the JSON file that was wrong apparently. I'm able to get it now. Commented Jan 22, 2015 at 12:36
  • 1
    @surfitscrollit Could you post your comment as an answer? I got useful answers that answers the topic but your comment was the thing that solved the issue. Commented Jan 22, 2015 at 12:41

6 Answers 6

4

On your local file you're getting a JSON parsing exception because your JSON is severely malformed. Try this format instead:

{
    "cities": [
        {
            "city": "Stockholm",
            "latitud": "59",
            "longitud": "18",
            "id": "sthlm"
        }
    ]
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can't do a cross-origin request for local files. Otherwise websites could request files on your computer at will.

See this question for more information. Suggested solutions include running a server in your machine so you end up calling the file via HTTP. file:// just isn't an acceptable "protocol" for making AJAX calls.

3 Comments

Well if Chrome doesn't allow it, how can I force it to allow it? Or how can I get around it?
Try another browser, possibly an older one, that still allows for XHR to run. Or run this inside a server, even a local one in your computer.
Try the suggestions on user1515126's answer. Your local server might have a restrictive Access Control policy. And it never hurts to avoid spaces in URL names (http://localhost:81/Webb/angular projekt/jsons/cities.json).
1

'http://localhost:81/Webb/angular projekt/jsons/cities.json' has a space in it. Could you try by eliminating the space between 'angular' and 'projekt'?

Making a get request to an external resource works fine, but whenever I do it locally things just doesn't seem to work.

Did you set the server's Access-Control-Allow-Origin response header to match your request's Origin header? Setting the response header to origin request header works.

Also how do you access your Angular page?

Comments

1

Try using a relative path instead of an absolute one:

$http.get('jsons/cities.json')

Or something along those lines, depending on your folder structure.

Edit: Here's a Plunkr showing it working.

Edit 2: It appears that the issue was actually the JSON being malformed. The correct format would be:

{
  "cities": [
    {   
        "city": "Stockholm", 
        "latitud": "59", 
        "longitud": "18",
        "id": "sthlm"
    }, 
    {
        "city": "Göteborg", 
        "latitud": "58", 
        "longitud": "12",
        "id": "gbg"
    },
    {
        "city": "Malmö", 
        "latitud": "55", 
        "longitud": "13",
        "id": "malmo"
    },
    {
        "city": "Umeå", 
        "latitud": "63", 
        "longitud": "20",
        "id": "umea"
    }
  ]
}

Comments

1

Presuming this will be static data. Define an object and refer to it as a script.

Include reference into index.html (or whatever)

<script src="../jsons/citiesJSON.js"></script>

create an object and pump in the data

var GLOBALDATA = {};
GLOBALDATA.citiesJSON =
{"cities": {
{   
    city: "Stockholm", 
    latitud: "59", 
    longitud: "18",
    id: "sthlm"
}, 
{
    city: "Göteborg", 
    latitud: "58", 
    longitud: "12",
    id: "gbg"
},
{
    city: "Malmö", 
    latitud: "55", 
    longitud: "13",
    id: "malmo"
},
{
    city: "Umeå", 
    latitud: "63", 
    longitud: "20",
    id: "umea"
    }
}
} ; // <-- it's a statement now

no need to request the data via HTTP

$scope.cities = GLOBALDATA.citiesJson;

Comments

0

I use relative path like $http.get('../jsons/cities.json'), but didn't work. Until I add support for .json file in web.config like this

<staticContent>
        <mimeMap fileExtension=".json" mimeType="application/json" />
      </staticContent>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.