5

我无法在 Angular 1.2.13 中创建成功的获取请求。

  var getProgress = function() {
      var promise = $http({method: 'GET', url: 'http://localhost:8080/project/local/some/getStatus'});

      promise.then(function(success) {
        alert(JSON.stringify(success));
      }, function(error) {
        alert(JSON.stringify(error));
      }, function(notify) {
        alert(JSON.stringify(notify));
      });
  };    

所以我试图从我的 REST Web 服务接收一些 JSON。为了测试该服务,我从浏览器(IE9、Firefox 27、Chrome 33)访问它,在所有浏览器中都可以正常工作。

但是,上面使用 angular 的代码总是提示我错误:

*{"data":"","status":404,"config":{"transformRequest":[null],"transformResponse":[null],"method":"GET","url":, "http://localhost:8080/project/local/some/getStatus"" headers":{"Accept":"application/json, text/plain, / "}}}*

使用wireshark我检查 HTTP 请求和 HTTP 响应,从浏览器和角度调用 Web 服务都返回 200和所需的 json 对象!!然而,角度提示我 404。

当我使用 ANGULAR 从 Firefox 发出获取请求并使用 Findbugs 进行调试时,在控制台中我得到 HTTP 代码 200,但 Angular 说 404。尝试调试 Angular 的代码无济于事,看不到任何奇怪的东西。

上面的代码在 IE9 中可以正常工作!

任何建议表示赞赏。

4

3 回答 3

3

@GeoffGenz && @BKM 是对的。CORS 是罪魁祸首。我想有几种方法可以解决这个问题。

  1. 在开发过程中,不要通过从文件加载页面来调试页面,而是将其部署在 Web 服务器内部,然后使用 firebugs 从那里进行调试。这是我的情况。我正在从 file:///...... 加载网页,并且我正在向 http:// 发出请求localhost......因为协议不同(文件与 http),所以请求具有不同的来源,如中所述https://developer.mozilla.org/en-US/docs/Web/JavaScript/Same_origin_policy_for_JavaScript。一旦部署在 JBoss 中,一切正常。
  2. 我没有尝试过的第二种解决方案是使用 JSONP Angular
  3. 最后一个是创建一个ContainerResponseFilter来更改标题?
@Provider
public class RespFilter implements ContainerResponseFilter {
    @Override
    public void filter(ContainerRequestContext reqContext, ContainerResponseContext respContext) throws IOException {
        respContext.getHeaders().putSingle("Access-Control-Allow-Origin", "*");
    }
}
于 2014-03-03T16:24:50.980 回答
0

我有同样的问题。但原因很简单,我向控制器添加了EnableCors属性,但我忘记在WebAPI配置中启用CORS

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.EnableCors();            
        ....
    }
}
于 2014-04-04T15:01:02.213 回答
-1

尝试这个:

$http({method: 'GET', url: 'http://localhost:8080/project/local/some/getStatus'}).
    success(function(data, status, headers, config) {
       alert(JSON.stringify(data));
    }).
    error(function(data, status, headers, config) {
      alert(JSON.stringify(data));
    });
于 2014-03-03T13:34:48.923 回答