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

我使用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信息:
图片描述

阅读 7.1k
2 个回答
  1. 强刷了吧

  2. 控制台开启了 disable cache 了吧

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题