2016-12-18 22 views
1

如何爲expressjs中的非靜態文件響應設置最大年齡參數。如何設置非靜態文件響應的最大年齡

我的代碼:

app.get('/hello', function(req, res) { 
    res.set('Content-Type', 'text/plain'); 
    res.set({'maxAge':5}); 
    res.send("Hello Message from port: " + port); 
    res.status(200).end() 
}) 

我嘗試這樣做:

res.set({'max-age':5}); 

而且這樣的:

res.set({'Cache-Control':'max-age=5'}); 

這是工作的罰款與res.SendFile(file,{maxAge: 5}) 但與靜態文件的問題我只在第一個http響應af中看到了「最大年齡」服務器啓動。

所有後續的響應報頭顯示「最大年齡= 0」,即使文件送達新鮮的(狀態200)

+1

如果您使用nginx的代理交接請求,最好在nginx的設置頭。 – num8er

回答

2

您不能設置與標題:

res.set({'maxAge':5}); 

或:

res.set({'max-age':5}); 

因爲而不是設置頭Cache-Control它將設置maxAgemax-age標頭,分別,這是無效的HTTP頭。

你可以將它設置:

res.set('Cache-Control', 'max-age=5'); 

或:

res.set({'Cache-Control': 'max-age=5'}); 

參見:

app.get('/hello', function(req, res) { 
    res.set('Content-Type', 'text/plain'); 
    res.set('Cache-Control', 'max-age=5'); 
    res.send("Hello Message from port: " + port); 
    res.status(200).end() 
}); 

您可以使用curl看標題:

curl -v http://localhost:3333/hello 

(只需使用你的端口而不是3333)

如果它不包括每個響應的Cache-Control頭那麼也許一些中間件是搞亂你的頭,或者你必須改變他們的代理服務器。

另外請記住,您使用max-age爲5秒,因此緩存很短。

參見:

+0

其目的是使緩存非常短。但我發現了這個問題。正如你所說,這是代理服務器搞亂了。我使用HAProxy負載均衡兩個快速服務器。再次感謝。 – user3151330

相關問題