角$ http.get总是得到错误本地消费RESTful服务 [英] Angular $http.get always get ERROR consuming local Restful Service

查看:167
本文介绍了角$ http.get总是得到错误本地消费RESTful服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个错误,我越来越迷惑,我已经用泽西一个简单的Java EE 7项目。

我在我的休息Rervice返回这个类:

  @XmlRootElement
公共类LocationDTOx {    私人长期身份证;
    私人字符串丝毫不差;
    私人字符串描述;
    私人龙父母;    // getter和setter方法​​...

在我的服务类我有:

  @Path(/位置)
公共类LocationService {    @得到
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Path(/ findlocation)
    公共LocationDTOx findLocation(){
        的System.out.println(findlocation);
        尝试{
            LocationDTOx X =新LocationDTOx();
            x.setDescription(描述);
            x.setId(0升);
            x.setParent(NULL);
            x.setTittle(丝毫不差......);
            返回X;
        }赶上(例外前){
            。Logger.getLogger(LocationService.class.getName())日志(Level.SEVERE,空,前);
        }
        返回null;
    }}

我100%肯定,我的休息是工作,如果我把这个在我的浏览器:

的http://本地主机:8080 / BIReportL战/ REST /位置/ findlocation

我得到这个JSON字符串:

{说明:说明,ID:0,丝毫不差:丝毫不差......}

该协议是在我的角度code时,code,其中我打电话的角度是越来越执行它的其余部分服务,但它只是让我有错误的部分:

  app.controller('questionsController',函数($范围,$ HTTP){
    // VAR URL =HTTP://本地主机:8080 / BIReportL战/ REST /位置/ findlocation
    // VAR URL =htt​​p://www.w3schools.com/angular/customers.php;
    VAR URL =htt​​p://127.0.0.1:8080/BIReportL-war/json.json;
    $ http.get(URL)
        。成功(
            功能(数据,状态,头,配置){
                警报(成功);
            })
        .error(功能(数据,状态,标题){
          警报('回购状态'+状态+'---标题:'+头);
        })
        。最后(
            功能(){
        });
});

我有意见的另一个地方的URL,我可以通过浏览器访问一个虚拟的JSON文件,我也得到相同的结果错误,奇怪的是,我试图用这个休息的公共JSON文件:

http://www.w3schools.com/angular/customers.php

和我得到的成功!我不知道为什么,我在做什么或什么,我已经错了,我的意思是,当我跟我的本地REST服务尝试,我看到它获取调用的日志,这是事实,但棱角分明的客户端越来越入一个错误。

在此先感谢您的帮助!

我使用:
* Glassfish的V4
*角

好吧,是关于CORS问题我只是把我的休息如下,所以这里是解决方案:

  @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Path(/ findlocation)
    市民反应findLocation(){
        的System.out.println(findlocation);
        尝试{
            LocationDTOx X =新LocationDTOx();
            x.setDescription(描述);
            x.setId(0升);
            x.setParent(NULL);
            x.setTittle(丝毫不差......);            返回Response.ok()
                    .entity(X)
                    .header(访问控制允许原产地,*)
                    .header(访问控制允许的方法,GET,POST,DELETE,PUT)
                    。建立();
        }赶上(例外前){
            。Logger.getLogger(LocationService.class.getName())日志(Level.SEVERE,空,前);
        }
        返回null;
    }


解决方案

如果AngularJS正在访问你的本地REST API,那你在一个的不同端口上的浏览器中运行它事实上的,它被视为一个不同的产地,每CORS规则(单独的端口指独立的起源)。


  

两页具有相同的起源,如果协议,端口(如果有的话
  指定),和主机是用于两页相同。


有关您的访问控制允许来源响应头,可以通过*将其设置为全部,或明确指定备用端口。这与事实,你的浏览器(和AngularJS)正试图通过规则,你可以找到的 MDN的页面上同根同源政策

这些规则不,当你直接在浏览器加载资源,作为原点(网页浏览器是由加载)是相同的端口你加载应用,的只是的资源,在那个原点(加上端口)。

该CORS标准包括遵守一定的响应头,如访问控制允许来源和访问控制允许的方法。

参考文献:

[/编辑]

I have an error and I am getting confuse, I have created a simple Java EE 7 project using Jersey.

I am returning this class in my Rest Rervice:

@XmlRootElement
public class LocationDTOx {

    private Long id;        
    private String tittle;    
    private String description;        
    private Long parent;

    //Getter and setters...

And in my service class i Have:

@Path("/location")
public class LocationService {

    @GET
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/findlocation")
    public LocationDTOx findLocation() {
        System.out.println("findlocation");
        try {
            LocationDTOx x = new LocationDTOx();
            x.setDescription("Description");
            x.setId(0l);
            x.setParent(null);
            x.setTittle("Tittle ...");
            return x;
        } catch (Exception ex) {
            Logger.getLogger(LocationService.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }    

}

I am 100% sure that my rest it is working , if I put this in my browser:

http://localhost:8080/BIReportL-war/rest/location/findlocation

I get this Json String:

{"description":"Description","id":0,"tittle":"Tittle ..."}

The deal is in my angular code, the code where I am calling the rest service from angular it is getting executed but it is just giving me the error part:

app.controller('questionsController', function ($scope, $http) {
    //var url = "http://localhost:8080/BIReportL-war/rest/location/findlocation";
    //var url = "http://www.w3schools.com/angular/customers.php";
    var url = "http://127.0.0.1:8080/BIReportL-war/json.json";
    $http.get(url)
        .success(
            function (data, status, headers, config) {
                alert("success");   
            })
        .error(function(data, status, headers) {
          alert('Repos status ' + status + ' --- headers : ' + headers);
        })
        .finally(
            function() {
        });
});

I have with comments another local URL to a dummy json file that I can access it by that browser, and also I get the same result an error, the weird thing is that I tried with this rest public json file:

http://www.w3schools.com/angular/customers.php

And I get the success !! I don't know why, what I am doing or what I have wrong, I mean when I try with my local rest service, I see that it is getting called in the logs, that is a fact, but the angular client is getting into an error.

Thanks in advance for your help !

I am using: *Glassfish V4 *Angular

Well, was about the CORS Issue I just put my rest as below, so here is the SOLUTION:

@Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/findlocation")
    public Response findLocation() {
        System.out.println("findlocation");
        try {
            LocationDTOx x = new LocationDTOx();
            x.setDescription("Description");
            x.setId(0l);
            x.setParent(null);
            x.setTittle("Tittle ...");

            return Response.ok()
                    .entity(x)
                    .header("Access-Control-Allow-Origin", "*")
                    .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
                    .build();
        } catch (Exception ex) {
            Logger.getLogger(LocationService.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }   

解决方案

If AngularJS is accessing your local REST API, the fact that you're running it in a browser on a different port, it counts as a different origin, per the rules of CORS (separate port means separate origin).

Two pages have the same origin if the protocol, port (if one is specified), and host are the same for both pages.

For your Access-Control-Allow-Origin response header, either set it to all via *, or specify the alternate ports explicitly. This has to do with the fact that your browser (and AngularJS) are attempting to play by the rules, which you can find on MDN's page on same origin policy.

These "rules" don't apply when you load the resource directly in your browser, as the origin (page your browser is loading from) is the same port, as you're loading just the resource, at that origin (plus port).

[Edit]

The CORS standards included adherence to certain response headers, such as Access-Control-Allow-Origin and Access-Control-Allow-Methods.

References:

[/Edit]

这篇关于角$ http.get总是得到错误本地消费RESTful服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆