【问题标题】:Angular grabbing JSON params with $http.get for one url but on anotherAngular 使用 $http.get 为一个 url 但在另一个上抓取 JSON 参数
【发布时间】:2017-10-30 15:22:34
【问题描述】:

我是 Angular 的新手,正在尝试一些基本的 UI 内容。我有一个 RESTful Spring 服务启动并运行。当我卷曲我的服务时:

curl http://myPersonalSite.com:1313/service/event?id=1

我收到一个 JSON 响应,其中包含“id”、“description”等内容。 使用相同的代码,但换掉我正在关注的示例中给出的 URL

curl http://rest-service.guides.spring.io/greeting

我还收到带有“id”和“content”的 JSON 响应。 示例 url 导致我运行时显示 ID

spring run app.groovy

...但是当我将其切换为我的服务 URL 时,不会显示 id。它似乎无法从我的服务的 JSON 响应中获取任何信息。我在这里错过了什么?!?

/public/index.html:

<html ng-app="demo">
<head>
    <title>Hello AngularJS</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
    <script src="hello.js"></script>
</head>
<body>
    <div ng-controller="Hello">
        <p>The ID is {{event.id}}</p>
    </div>
</body>

/public/hello.js:

angular.module('demo', []) .controller('Hello', function($scope, $http) { $http.get('http://rest-service.guides.spring.io/greeting'). // this works //$http.get('http://myPersonalSite.com:1313/service/event?id=1'). // this doesn't work then(function(response) { $scope.event = response.data; }); });

app.groovy - 简单:

@Controller class JsApp { }

...然后我运行spring run app.groovy,示例 URL 在浏览器中呈现 id,但我的 URL 呈现页面但没有 id。同样,两个 URL 的 curl 都返回包含“id”键的 JSON。我已经阅读了一些关于 JSON 字符串与对象的内容,这似乎不是问题,here。任何帮助将不胜感激。

注意 - 以下线程类似,但略有不同jQuery - .get works for 1 URL but not another

【问题讨论】:

    标签: angularjs json rest service


    【解决方案1】:

    我猜你的请求被 CORS 政策阻止了。您可以检查您的浏览器控制台是否有任何错误消息,例如“...已被 CORS 策略阻止:请求的资源上不存在 'Access-Control-Allow-Origin' 标头”。

    如果您检查 Chrome 的网络选项卡,rest-service 响应实际上设置了 Access-Control-Allow-Origin。

    如果请求的资源的域与页面域不同并且没有在服务器端设置适当的 Access-Control-Allow-Origin 标头,浏览器将阻止 ajax 请求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-18
      • 2020-08-18
      • 2014-11-15
      相关资源
      最近更新 更多