Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular $http.get to localhost, always returns 404. 200 in browser

I can't create a successful get request in 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));
      });
  };    

So I'm trying to receive some JSON from my REST web service. To test the service, I access it from the browsers(IE9,Firefox 27, Chrome 33) works fine in all of them.

The above code using angular however, always prompts me with the error:

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

Using wireshark I check the HTTP request and HTTP response, both calling the web service from browser and from angular returns 200, and the desired json object!! Nevertheless angular prompts me with 404.

When I make the get request from Firefox USING ANGULAR and debug using Findbugs, in the console I get HTTP Code 200, nevertheless Angular says 404. Tried debuging angular's code to no avail, can't see anything strange.

The above code works correctly in IE9!

Any suggestions are appreciated.

like image 919
dalvarezmartinez1 Avatar asked Nov 01 '22 04:11

dalvarezmartinez1


1 Answers

@GeoffGenz && @BKM were right. CORS is to blame. I imagine there are several ways around the problem.

  1. During development, don't debug your page by loading it from file, instead deploy it, inside of your web server, and debug from there using firebugs. This was my case. I was loading the webpage from file:///...... and I was making a request to http://localhost... Because the protocol is different (file vs http) the request has different origin, as explained in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Same_origin_policy_for_JavaScript . Once deployed in JBoss everything works.
  2. A second solution, which I haven't try would be to use JSONP Angular
  3. The last one would be to create a ContainerResponseFilter to alter the headers?
@Provider
public class RespFilter implements ContainerResponseFilter {
    @Override
    public void filter(ContainerRequestContext reqContext, ContainerResponseContext respContext) throws IOException {
        respContext.getHeaders().putSingle("Access-Control-Allow-Origin", "*");
    }
}
like image 199
dalvarezmartinez1 Avatar answered Nov 11 '22 13:11

dalvarezmartinez1