javascript 无法使用 Angular 向本地 JSON 文件发出 $http.get 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28088568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:23:38  来源:igfitidea点击:

Unable to make a $http.get request to a local JSON file using Angular

javascriptjsonangularjshttp

提问by Chrillewoodz

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.getrequest to work for some reason. What should I do?

我正在制作一个天气应用程序,我需要从控制器中获取本地 JSON 文件,然后对数据进行处理。但是,由于某种原因,我无法获得本地$http.get工作请求。我该怎么办?

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.jsonbut that throws this error:

我也尝试使用,jsons/cities.json但这会引发此错误:

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.

向外部资源发出 get 请求可以正常工作,但是每当我在本地执行此操作时,事情似乎都不起作用。

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

我试图获取的 JSON 文件如下所示:

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

回答by JAAulde

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

在您的本地文件中,您收到 JSON 解析异常,因为您的 JSON 格式严重错误。试试这个格式:

{
    "cities": [
        {
            "city": "Stockholm",
            "latitud": "59",
            "longitud": "18",
            "id": "sthlm"
        }
    ]
}

回答by Chrillewoodz

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

您不能对本地文件进行跨域请求。否则网站可能会随意请求您计算机上的文件。

See this questionfor 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 调用文件。file://只是不是进行 AJAX 调用的可接受的“协议”

回答by user1515126

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

' http://localhost:81/Webb/angularprojekt/jsons/cities.json' 中有一个空格。您可以尝试消除“角度”和“项目”之间的空间吗?

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

向外部资源发出 get 请求可以正常工作,但是每当我在本地执行此操作时,事情似乎都不起作用。

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.

您是否设置了服务器的 Access-Control-Allow-Origin 响应标头以匹配您的请求的 Origin 标头?将响应标头设置为原始请求标头有效。

Also how do you access your Angular page?

另外你如何访问你的 Angular 页面?

回答by surfitscrollit

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 Plunkrshowing it working.

编辑:这是一个显示它正在工作的 Plunkr

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

编辑 2:看来问题实际上是 JSON 格式错误。正确的格式是:

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

回答by Jojo

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

假设这将是静态数据。定义一个对象并将其称为脚本。

Include reference into index.html (or whatever)

将引用包含在 index.html(或其他)中

<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

无需通过 HTTP 请求数据

$scope.cities = GLOBALDATA.citiesJson;

回答by Nedim

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

我使用像 $http.get('../jsons/cities.json') 这样的相对路径,但没有用。直到我像这样在 web.config 中添加对 .json 文件的支持

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