Why is $http.get returning 304 error

All we need is an easy explanation of the problem, so here it is.

I’m new to angular and having trouble with a service that always worked, until it didn’t. My service has the following call.

this.getForms = function() {
    return $http.get("/forms").
    then(function(response) {
        return response;
    }, function(response) {
        alert("Error finding forms.");

When the page is refreshed (safari) getForms is trigged, $http.get is called, my Node.js/Express server forms endpoint returns the forms data properly.

app.get("/forms", function (req, res) {
    Form.find({}, function (err, docs) {
        if (err) {
            server.handleError(res, err.message, "Failed to get forms.");
        } else {

But instead of the JSON I get a 304 error, which indicates the data is available in cache. But the 304 response header has an empty data string, so it’s not returning any data from the cache.

My questions are

1) Why is it calling my server if the data is available in cache?

2) How can I tell it to not cache this call so the page can update with forms correctly?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Edit: Looks like there could be a potential issue with Safari. See this post as well. NodeJS/express: Cache and 304 status code

You might be misunderstanding what the 304 status code means. 304 is not an error; it just means that the resource you are requesting from the server has not changed. The response is meant to not contain data as it expects the client to have cached it somewhere.

For example, web browsers will try to cache an image so the server doesn’t have to send it over the network again if the user reloads the page or returns to it later. However, the browser needs a way to know whether the image is up to date or not. If the server sends a 304 the browser knows it can continue to use the copy in its cache.

In your case you should implement some sort of caching to return the previous response if you recieve a 304.
Alternatively, I believe you could add these headers to the request to force it to return data

 Cache-Control: no-cache, no-store, must-revalidate
 Pragma: no-cache
 Expires: 0

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply