NodeJS/express:缓存和 304 状态码 [英] NodeJS/express: Cache and 304 status code

查看:54
本文介绍了NodeJS/express:缓存和 304 状态码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我重新加载一个用 express 制作的网站时,我在 Safari(而不是 Chrome)中得到一个空白页面,因为 NodeJS 服务器向我发送了一个 304 状态代码.

When I reload a website made with express, I get a blank page with Safari (not with Chrome) because the NodeJS server sends me a 304 status code.

如何解决这个问题?

当然,这也可能只是 Safari 的问题,但实际上它在所有其他网站上都可以正常工作,所以它也必须是我的 NodeJS 服务器上的问题.

Of course, this could also be just a problem of Safari, but actually it works on all other websites fine, so it has to be a problem on my NodeJS server, too.

为了生成页面,我使用 Jade 和 res.render.

To generate the pages, I'm using Jade with res.render.

更新:这个问题似乎是因为 Safari 在重新加载时发送 'cache-control': 'max-age=0'.

Update: It seems like this problem occurs because Safari sends 'cache-control': 'max-age=0' on reload.

更新 2:我现在有一个解决方法,但有更好的解决方案吗?解决方法:

Update 2: I now have a workaround, but is there a better solution? Workaround:

app.get('/:language(' + content.languageSelector + ')/:page', function (req, res)
{
    // Disable caching for content files
    res.header("Cache-Control", "no-cache, no-store, must-revalidate");
    res.header("Pragma", "no-cache");
    res.header("Expires", 0);

    // rendering stuff here…
}

更新 3:所以目前完整的代码部分是:

Update 3: So the complete code part is currently:

app.get('/:language(' + content.languageSelector + ')/:page', pageHandle);

function pageHandle (req, res)
{
    var language = req.params.language;
    var thisPage = content.getPage(req.params.page, language);

    if (thisPage)
    {
        // Disable caching for content files
        res.header("Cache-Control", "no-cache, no-store, must-revalidate");
        res.header("Pragma", "no-cache");
        res.header("Expires", 0);

        res.render(thisPage.file + '_' + language, {
            thisPage : thisPage,
            language: language,
            languages: content.languages,
            navigation: content.navigation,
            footerNavigation: content.footerNavigation,
            currentYear: new Date().getFullYear()
        });
    }
    else
    {
        error404Handling(req, res);
    }
}

推荐答案

最简单的解决方案:

app.disable('etag');

如果您想要更多控制,这里的替代解决方案:

Alternate solution here if you want more control:

http://vlasenko.org/2011/10/12/expressconnect-static-set-last-modified-to-now-to-avoid-304-not-modified/

这篇关于NodeJS/express:缓存和 304 状态码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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