Angular $ http.get到localhost,总是在浏览器中返回404. 200

dal*_*ez1 5 json angularjs angular-http

我无法在Angular 1.2.13中创建成功的get请求.

  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));
      });
  };    
Run Code Online (Sandbox Code Playgroud)

所以我试图从我的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""标题":{"接受":"application/json,text/plain,/ "}}}*

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

当我从Firefox USING ANGULAR发出get请求并使用Findbugs进行调试时,在控制台中我获得了HTTP Code 200,然而Angular说404.尝试调整角度的代码无济于事,看不出有什么奇怪的.

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

任何建议表示赞赏.

dal*_*ez1 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", "*");
    }
}
Run Code Online (Sandbox Code Playgroud)