您的位置:首页技术文章
文章详情页

html5 - node静态资源服务器设置了Cache-Control,但浏览器从来不走304

【字号: 日期:2023-10-10 16:02:23浏览:133作者:猪猪

问题描述

我使用node作静态资源服务器,返回一张普通的png图片。现在我给这个响应设置了Cecha-Control,希望可以让浏览器进行缓存。可是每次我刷新页面,都是返回200,从服务器请求资源。请问应该如何设置才能使用浏览器的缓存呢?

下面是node端代码:

const fs = require(’fs’)const http = require(’http’)const url = require(’url’)const server = http.createServer((req, res) => { let pathname = url.parse(req.url).pathname let realPath = ’assets’ + pathname console.log(realPath) fs.readFile(realPath, 'binary', function(err, file) { if (err) { res.writeHead(500, {’Content-Type’: ’text/plain’}) res.end(err) } else { res.writeHead(200, {’Access-Control-Allow-Origin’: ’*’,’Content-Type’: ’image/png’,’ETag’: '666666',’Cache-Control’: ’max-age=31536000, public’,’Expires’: ’Mon, 07 Sep 2026 09:32:27 GMT’ }) res.write(file, 'binary') res.end() } })})server.listen(80)console.log(’Listening on port: 80’)

请求header信息:html5 - node静态资源服务器设置了Cache-Control,但浏览器从来不走304

问题解答

回答1:

强刷了吧

控制台开启了 disable cache 了吧

回答2:

已经解决了,是刷新的问题。手动刷新会强制浏览器走服务器,只要在新窗口重新打开当前页面就能看到200 (from cache)了

标签: Html5