最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Unable to make a $http.get request to a local JSON file using Angular - Stack Overflow

programmeradmin3浏览0评论

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 (.3.10/angular.min.js:14:156)
at Yb (.3.10/angular.min.js:77:190)
at .3.10/angular.min.js:78:50
at s (.3.10/angular.min.js:7:302)
at Yc (.3.10/angular.min.js:78:32)
at c (.3.10/angular.min.js:79:165)
at .3.10/angular.min.js:112:343
at l.$eval (.3.10/angular.min.js:126:193)
at l.$digest (.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"
    }
}
}

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./ajax/libs/angularjs/1.3.10/angular.min.js:14:156)
at Yb (https://ajax.googleapis./ajax/libs/angularjs/1.3.10/angular.min.js:77:190)
at https://ajax.googleapis./ajax/libs/angularjs/1.3.10/angular.min.js:78:50
at s (https://ajax.googleapis./ajax/libs/angularjs/1.3.10/angular.min.js:7:302)
at Yc (https://ajax.googleapis./ajax/libs/angularjs/1.3.10/angular.min.js:78:32)
at c (https://ajax.googleapis./ajax/libs/angularjs/1.3.10/angular.min.js:79:165)
at https://ajax.googleapis./ajax/libs/angularjs/1.3.10/angular.min.js:112:343
at l.$eval (https://ajax.googleapis./ajax/libs/angularjs/1.3.10/angular.min.js:126:193)
at l.$digest (https://ajax.googleapis./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"
    }
}
}
Share Improve this question asked Jan 22, 2015 at 12:17 ChrillewoodzChrillewoodz 28.3k23 gold badges99 silver badges186 bronze badges 9
  • 1 you aren't passing a valid URI. you can't have spaces in the URI. – Claies 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. – shauneba Commented Jan 22, 2015 at 12:32
  • @AndrewCounts I get the same result without. – Chrillewoodz 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. – Chrillewoodz Commented Jan 22, 2015 at 12:36
  • 1 @surfitscrollit Could you post your ment as an answer? I got useful answers that answers the topic but your ment was the thing that solved the issue. – Chrillewoodz Commented Jan 22, 2015 at 12:41
 |  Show 4 more ments

6 Answers 6

Reset to default 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"
        }
    ]
}

You can't do a cross-origin request for local files. Otherwise websites could request files on your puter 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.

'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?

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"
    }
  ]
}

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;

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>
发布评论

评论列表(0)

  1. 暂无评论