Tag Archives: http 304

Angular $http and 304 Not Modified

Angular has in issue with HTTP status codes: it believes only HTTP responses with a status code between 200 and 299 indicate a successful response. However, a common, successful HTTP response is 304 Not Modified. If $http receives a response with this status, the error closure is called. What’s worse is that there seems to be no way to get to the response data from this closure.

One way I’ve found to get around this problem is with cache busting – a technique normally reserved for ensuring you get the latest CSS file to the browser. Consider the following code.


$http.get('http://www.mydomain.com/my/endpoint')
.then(
    function(response){
        $scope.data = response.data;
    },
    function(error){
        // Here we get a 304 Not Modified but we can't do anything
    }
);

To get around this problem, try adding a timestamp to the endpoint.


$http.get('http://www.mydomain.com/my/endpoint' + '?t=' + (new Date()).getTime())
.then(
    function(response){
        $scope.data = response.data;
    },
    function(error){
        // Handle error
    }
);

Now we are sure to get a 200 OK response assuming the request was successful because the URL will be different for each request.