简体   繁体   English

为什么$ http.get返回304错误

[英]Why is $http.get returning 304 error

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. 刷新页面(safari)时触发getForms,调用$ http.get,我的Node.js / Express服务器表单端点正确返回表单数据。

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

But instead of the JSON I get a 304 error, which indicates the data is available in cache. 但是,我得到的是304错误,而不是JSON,这表明数据在缓存中可用。 But the 304 response header has an empty data string, so it's not returning any data from the cache. 但304响应头有一个空数据字符串,因此它不会从缓存中返回任何数据。

My questions are 我的问题是

1) Why is it calling my server if the data is available in cache? 1)如果数据在缓存中可用,为什么要调用我的服务器?

2) How can I tell it to not cache this call so the page can update with forms correctly? 2)如何告诉它不缓存此调用,以便页面可以正确更新表单?

Edit: Looks like there could be a potential issue with Safari. 编辑:看起来Safari可能存在潜在问题。 See this post as well. 也请看这篇文章。 NodeJS/express: Cache and 304 status code NodeJS / express:缓存和304状态代码

You might be misunderstanding what the 304 status code means. 您可能误解304状态代码的含义。 304 is not an error; 304不是错误; 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. 例如,Web浏览器将尝试缓存图像,以便服务器不必再次通过网络发送它,如果用户重新加载页面或稍后返回该页面。 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 在你的情况下,如果你收到304,你应该实现某种缓存来返回先前的响应。或者,我相信你可以将这些标题添加到请求中以强制它返回数据

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM