【问题标题】:Angular http get does not work for localhost response status -1Angular http get 不适用于 localhost 响应状态 -1
【发布时间】:2021-05-23 14:39:00
【问题描述】:

我有一个简单的网络服务:

@SpringBootApplication
@RestController
@RequestMapping(value="hello")
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @RequestMapping(value="/{firstName}/{lastName}",method = RequestMethod.GET, produces = "application/json")
    public String hello( @PathVariable("firstName") String firstName,
                     @PathVariable("lastName") String lastName) {

        return String.format("{\"message\":\"Hello %s %s\"}", firstName, lastName);

    }

}

我在 8081 端口运行,我可以从浏览器获取它。

但是,从角度来看,我得到错误,响应状态 -1:

<div ng-app="myApp" ng-controller="myCtrl"> 

<p>Today's welcome message is:</p>

<h1>{{myWelcome}}</h1>

</div>


<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  $http.get("http://localhost:8081/hello/test/gfgg")
  .then(function success(response) {
      $scope.myWelcome = "response.data";
  }, 
  function error(response) {      // Response status code 4xx and 5xx
            console.log("error");
            $scope.myWelcome = response.status + ": " + JSON.stringify(response);
         });
});
</script>

</body>
</html>

当我使用一些公共服务时,例如 http://md5.jsontest.com/?text=1234,角度工作正常。

有人知道如何让本地服务以 Angular 工作吗?

【问题讨论】:

  • -1 的状态通常会发生 CORS 错误。您应该会在开发者控制台中看到该消息。

标签: angularjs cors same-origin-policy


【解决方案1】:

谢谢乔治。是的,这是 CORS 错误。当我打开开发者控制台时,我可以看到: CORS 策略已阻止从源“null”访问“http://localhost:8080/v1/organizations/e254f8c-c442-4ebe-a82a-e2fc1d1ff78a/licenses/f3831f8c-c338-4ebe-a82a-e2fc1d1ff78a”处的 XMLHttpRequest : 请求的资源上不存在“Access-Control-Allow-Origin”标头。

为了解决这个问题,在我的 RestController 中,我添加了: @CrossOrigin("*")

然后我可以从 Angular 客户端调用中获取服务结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-08
    • 2015-10-24
    • 2016-05-26
    • 2018-02-14
    • 2018-10-27
    • 2017-01-15
    • 1970-01-01
    • 2016-04-03
    相关资源
    最近更新 更多