为什么$ http.get返回304错误 [英] Why is $http.get returning 304 error

查看:897
本文介绍了为什么$ http.get返回304错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个刚开始有角度的人,并且遇到了一个始终有效的服务,直到它没有。我的服务有以下电话。

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.");
    });
};

刷新页面时(safari)触发getForms,调用$ http.get,我的节点.js / Express服务器表单端点正确返回表单数据。

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 {
            res.status(200).json(docs);
        }
    });
});

但是我得到304错误,而不是JSON,这表示数据在缓存中可用。但是304响应标头有一个空的数据字符串,因此它不会从缓存中返回任何数据。

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.

我的问题是

1)如果数据在缓存中可用,为什么要调用我的服务器?

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

2)我怎么能告诉它不要缓存这个调用所以页面可以正确更新表格吗?

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

推荐答案

编辑:看起来Safari可能存在潜在问题。也请看这篇文章。 NodeJS / express:缓存和304状态代码

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

您可能误解了304状态代码的含义。 304不是错误;它只是意味着您从服务器请求的资源没有改变。响应意味着不包含数据,因为它希望客户端在某处缓存它。

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.

例如,Web浏览器会尝试缓存图像,这样如果用户重新加载页面或返回页面,服务器就不必再通过网络发送它后来。但是,浏览器需要一种方法来了解图像是否是最新的。如果服务器发送304,则浏览器知道它可以继续在其缓存中使用该副本。

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.

在您的情况下,您应该实现某种缓存以返回先前的响应如果您收到304.
或者,我相信您可以将这些标题添加到请求中以强制它返回数据

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

这篇关于为什么$ http.get返回304错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆